├── .DS_Store
├── .gitignore
├── .ipynb_checkpoints
└── README-checkpoint.md
├── 3-simple-moving-averages-performance-testing.ipynb
├── Advanced Python Trade Techniques
├── BTC - EMA-23 - Kalman
├── Binance Trading Bot
├── .DS_Store
├── .ipynb_checkpoints
│ ├── README-checkpoint.md
│ ├── binance_bot-checkpoint.py
│ ├── binance_bot_SAMPLE-checkpoint.py
│ ├── binance_bot_v3-checkpoint.py
│ ├── config-checkpoint.py
│ ├── get_balance-checkpoint.py
│ ├── marquee-checkpoint.py
│ ├── remove_this_prefix_after_configured_config-checkpoint.py
│ ├── requirements-checkpoint.txt
│ ├── safemode_binance_bot-checkpoint.py
│ └── supertrend_atr_multiplier_test-checkpoint.py
├── README.md
├── binance_bot.py
├── binance_bot_SAMPLE.py
├── config.py
├── get_balance.py
├── marquee.py
├── requirements.txt
├── safemode_binance_bot.py
└── supertrend_atr_multiplier_test.py
├── Cofee Trading™ - DASCIENT
├── EV Data
├── Hyperspectralism
├── Jason - Binance Scratchpad
├── README.md
├── log_server.py
├── message.py
└── test.py
├── LICENSE
├── La Vie Bohem - Part 2
├── La Vie Bohem - Part 3
├── La Vie Bohem - Part 4
├── La Vie Bohem - Whispers of the Infinite
├── La View Bohem
├── Parquet
├── .DS_Store
├── .ipynb_checkpoints
│ ├── supertrend_visual_BTC-USDT-checkpoint.jpg
│ ├── supertrend_visual_ETH-USDT-checkpoint.jpg
│ ├── supertrend_visual_LTC-USDT-checkpoint.jpg
│ └── supertrend_visualizer-checkpoint.py
├── DOGE-USDT.parquet
├── README.md
├── requirements.txt
├── supertrend_visual_BTC-USDT.jpg
├── supertrend_visual_ETH-USDT.jpg
├── supertrend_visual_LTC-USDT.jpg
└── supertrend_visualizer.py
├── README.md
├── RL-Binance
├── .DS_Store
├── .ipynb_checkpoints
│ ├── RL-bot_7-checkpoint.py
│ ├── ScratchPaper-checkpoint.ipynb
│ └── test-checkpoint.py
├── 2022_03_26_09_39_VTHO_Crypto_trader
│ ├── .DS_Store
│ ├── .ipynb_checkpoints
│ │ ├── Parameters-checkpoint.json
│ │ └── log-checkpoint.txt
│ ├── 1283.77_Crypto_trader_Actor.h5
│ ├── 1283.77_Crypto_trader_Critic.h5
│ ├── 1284.68_Crypto_trader_Actor.h5
│ ├── 1284.68_Crypto_trader_Critic.h5
│ ├── Parameters.json
│ └── log.txt
├── DOGE-USDT.parquet
├── README.md
├── RL-bot_7.py
├── ScratchPaper.ipynb
├── VTHO-USDT.parquet
├── __pycache__
│ ├── indicators.cpython-38.pyc
│ ├── model.cpython-38.pyc
│ ├── multiprocessing_env.cpython-38.pyc
│ └── utils.cpython-38.pyc
├── indicators.py
├── log_server.py
├── message.py
├── model.py
├── multiprocessing_env.py
├── requirements.txt
├── runs
│ └── 2022_03_26_09_39_Crypto_trader
│ │ └── events.out.tfevents.1648312935.donutpy.local
├── test.py
└── utils.py
├── Reinforced Learning for Crypto Trading
├── Robinhood Trading Bot
├── .DS_Store
├── .ipynb_checkpoints
│ ├── config-checkpoint.py
│ ├── marquee_robin_bot-checkpoint.py
│ ├── robin_bot_v1-checkpoint.py
│ ├── robin_bot_v2-checkpoint.py
│ └── robin_supertrend_visualizer-checkpoint.py
├── __pycache__
│ └── config.cpython-38.pyc
├── client_robin_bot.py
├── config.py
├── get_balance.py
├── marquee_robin_bot.py
└── robin_supertrend_visualizer.py
├── Short Squeeze Finder
├── crypto-forecast-using-statsmodels-varmax.ipynb
├── cryptofore-arima-forecasting-approach.ipynb
├── cryptoforecast-univariate-lstm-rnn-approach.ipynb
├── daily-binance-trade-signals.ipynb
├── hello universe!
├── supertrend_visualizer_parquet.py
├── un-oracle-nigmatique.ipynb
└── yahoo-top-gainers-kalman-forecasting-model.ipynb
/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DaScient/SuperTrendTradingBot/f8070baa52422d1d5c39b646047a305db295b873/.DS_Store
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *config.py
--------------------------------------------------------------------------------
/.ipynb_checkpoints/README-checkpoint.md:
--------------------------------------------------------------------------------
1 | # SuperTrendTradingBot
2 | A DaScient, LLC proprietary software & non-ML approach to the application of the SuperTrend indicator designed to execute buy & sell orders to Binance.US using python.
3 |
4 | ---
5 |
6 | ## Welcome to the Trading Bot - SuperTrend Readme! :robot:
7 |
8 | The purpose of this repository is to document the development of our very first trading bot. The bot will be broken out into 3 broad classes:
9 |
10 | 1. Data Class
11 | 2. Trade Strategy Class
12 | 3. Execution Class
13 |
14 | ### What's Needed?
15 |
16 | Although our team is working very hard to get the fully user-friendly app developed & deployed, there will still be plenty of time to test the bot on your own as we work through our goals and plans for the future. Feel free to fork, star, and/or watch for any of our updates here on GitHub.
17 |
18 | Here's what you'll currently need in order to execute the bot locally on your machine. (An introductory Python crash course probably wouldn't hurt.) If you do run with it we seek your inputs, suggestions, and ideas that you can prove have a place in our code. Whether it's to help the bot run more efficiently or how we can better scale our project. Your thoughts are welcome! This program is far from perfect, but your support and growing interest we give us the encouragement we need to get this released and trading as smoothly as we possible. Don't hesitate to contact us if there's anything we can do to help: contact@dascient.com
19 |
20 | #### Requirements
21 | 1. Latest Python (3.9.7)
22 | 2. Jupyter Notebook - Anaconda (mini-conda will certainly suffice)
23 | 3. Binance.US crypto brokerage account. (API_KEY, API_SECRET)
24 | 4. Lastly, you'll need this repository.
25 |
26 | Don't have Binance.US? [Sign up here!](https://accounts.binance.us/en/register?ref=52441695)
27 | 1. After login, go to the menu settings and find API MANAGEMENT.
28 | 2. Create API.
29 | 3. Save and KEEP ULTRA SAFE your api.key & api.secret (in a config.py, follow format.)
30 | 4. Then go into your terminal > find where the binance_bot_vX.py is located > run >>python binance_bot_vX.py)
31 |
32 | ### SuperTrend - Data :computer:
33 |
34 | This class will consist of a CCXT connection into Binance.US WebSocket interface that will feed live cryptocurrency data in the form of candle sticks; Open, High, Low, Close (OHLC).
35 |
36 | We also apply rolling averages, upper/lower Bollinger bands, and binary variables that evaluates uptrend/downtrend intervals.
37 |
38 | ### Resources & Repositories Used
39 | [Part Time Larrys (hackingthemarkets)'s supertrend-crypto-bot](https://github.com/hackingthemarkets/supertrend-crypto-bot)
40 | [Part Time Larrys (hackingthemarkets)'s binance-tutorials](https://github.com/hackingthemarkets/binance-tutorials)
41 | [CCXT - BinanceUS](https://github.com/ccxt/ccxt)
42 | [Binance Full History, 2017 - 2020](https://www.kaggle.com/jorijnsmit/binance-full-history)
43 |
44 |
45 | ### Trade Strategy :chart_with_upwards_trend:
46 |
47 | Like many things in life, sometimes one needs a little variety. There is no shortage of trade strategies to apply to our bot. With this in mind, the strategy class will be designed to be modular.
48 | That is, it is to be developed with "plug-and-play" design in order to develop different trading strategies over time. As long as the strategy sends a buy/sell signal for the execution, it will function properly.
49 |
50 | ### Execution :moneybag:
51 |
52 | Once the trade signal is sent, the execution class with send the order to Binance.US via ccxt.exchange. For this execution to work, the user will need to verify their identity at CryBot startup.
53 |
54 | Relax, have fun, and don't forget to drink plenty of water! :tada::rocket::full_moon:
55 |
--------------------------------------------------------------------------------
/3-simple-moving-averages-performance-testing.ipynb:
--------------------------------------------------------------------------------
1 | {"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.7.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":3104752,"sourceType":"datasetVersion","datasetId":1895907}],"dockerImageVersionId":30170,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"source":"
","metadata":{},"cell_type":"markdown"},{"cell_type":"markdown","source":"# Welcome to our Universe\n## [@donutz.ai](www.donutz.ai/#)\n[Read our blog about how & why this notebook was written.](https://medium.com/coinmonks/3-simple-moving-averages-trade-strategy-performance-test-2194f423d36b?source=user_profile---------1----------------------------)","metadata":{}},{"cell_type":"code","source":"!pip install -U vectorbt\n!pip install -U \"vectorbt[full]\"\n!pip install pandas_ta\n# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\nfrom IPython.display import clear_output\nfrom dateutil.tz import tzlocal\nimport matplotlib.pyplot as plt\nfrom datetime import datetime\nimport pandas_ta as ta # https://github.com/twopirllc/pandas-ta\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport time \n\nimport warnings # feel free to remove these\nwarnings.filterwarnings('ignore')\n\n# performance metrics package\n# https://vectorbt.dev\nimport vectorbt as vbt\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n for filename in filenames:\n print(os.path.join(dirname, filename))\n\nclear_output()","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"execution_failed":"2025-01-01T06:32:46.754Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Three Moving Averages Strategy + VectorBT's Performance Metrics Package\n## For backtesting combinations of three simple moving averages","metadata":{"execution":{"execution_failed":"2025-01-01T06:32:46.755Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Upload a couple of historical cryptocurrency data. ","metadata":{}},{"cell_type":"code","source":"btc = pd.read_csv('../input/top-8-crypto-currency-data/BTC-EUR.csv')\neth = pd.read_csv('../input/top-8-crypto-currency-data/ETH-EUR.csv')\n\n# live\nbtc_live = pd.read_csv('https://www.cryptodatadownload.com/cdd/Binance_BTCUSDT_1h.csv',header=1)\n\nbtc_live['Close'].plot(figsize=(20,7))\nplt.title(\"(Not-so) MOST RECENT LIVE BTC Chart\")","metadata":{"execution":{"execution_failed":"2025-01-01T06:32:46.755Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Pandas_TA has a tsignals function that allows us to set boolean entities as our \"entry\" & \"exit\" signals. You might find the algorithm below to be a bit strange, but my goal was to try and determine the best Three-Moving-Averages sma combinations. I thought it would be interesting to reiterate through the multiplicative combinations of trading against thee (3) simple moving averages.","metadata":{}},{"cell_type":"code","source":"# https://github.com/twopirllc/pandas-ta#performance-metrics\n\n# define True/False signal parameters for 3 SMAs\ndef tsignals(df,a,b,c):\n # Create the \"Golden Cross\" conditions\n # three simple moving average with their periods set as variables\n smaA = df.ta.sma(a, append=True)\n smaB = df.ta.sma(b, append=True)\n smaC = df.ta.sma(c, append=True)\n close = df.Close[len(df)-1]\n \n # when the smaA cross above smaB and smaC, we give a \"True\" signal for entries\n # IMPORTANT part of assumed straegy\n \n #df[\"GC\"] = (smaA > smaB) & (smaB > smaC)\n df[\"GC\"] = (close > smaA) & (smaA > smaB) & (smaB > smaC)\n \n \n golden = df.ta.tsignals(df.GC, asbool=True, append=True)\n\n # Create the Signals Portfolio Performance Assessment report\n pf = vbt.Portfolio.from_signals(df.Close, entries=golden.TS_Entries, exits=golden.TS_Exits, freq=\"D\", \n # set initial principal and other params, docs fuond in vectorbt\n init_cash=100, fees=0.0025, slippage=0.0025)\n\n\n # values from report we care about\n ev = pf.stats()['End Value']\n re = pf.stats()['Total Return [%]']\n \n return pd.Series([ev,re,a,b,c]),df,pf,golden","metadata":{"execution":{"execution_failed":"2025-01-01T06:32:46.755Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# range of curious movAvg values & initialize results frame\n\n# after many trials, I decided the best ranges for a,b,c are as follows:\nsma_a, sma_b, sma_c, results = list(range(7,40)),list(range(41,120)),list(range(121,135)),[]\n\n# for the sake of computation efficiency...\ndf = eth\n\n# re(re(iteration))\n# this will take a while to run, \n# it evaluates profit/loss outcomes\n# by trying each sma(a,b,c) combinations.\n\nthresh = 0#15 # hoping to display only results that yield above 15% profit\nfor c in sma_c:\n for b in sma_b:\n for a in sma_a:\n if tsignals(df,a,b,c)[0][1] > thresh:\n\n try:\n print(f\"\\n*Testing: sma_{a}, sma_{b}, sma_{c}*\\n\")\n print(f\"*Score: {tsignals(df,a,b,c)[0][1]}*\\n\")\n results.append(tsignals(df,a,b,c)[0])\n clear_output()\n except:\n print(f\"No results yielding over {thresh}.\")\n\nres = pd.DataFrame(results)\nbest_res = res.sort_values(res.columns[1],ascending=False).head(3).reset_index(drop=True)\nprint(\"Best resolution:\\nEnd Principal, % Return, SMAa, SMAb, SMAc\")\nprint(best_res)","metadata":{"execution":{"execution_failed":"2025-01-01T06:32:46.755Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# highest yielding sma_value\na = best_res[2][0]\nb = best_res[3][0]\nc = best_res[4][0]\nprint(f\"\\nBest SMA Throuple: {a}, {b}, {c}\")\nprint(f\"Number of results evaluated: {len(results)}\")\n\n########################################################\n\n# le winner\ndf, pf = tsignals(df,a,b,c)[1], tsignals(df,a,b,c)[2].stats()\ngolden = tsignals(df,a,b,c)[3]\n# params\nfig, ax = plt.subplots(figsize=(20, 8))\n\n# plot\nax.plot(df.Close, color = 'black', label = 'closePrice')\nax.plot(df.ta.sma(a), color = 'orange', label = f'sma-{a}')\nax.plot(df.ta.sma(b), color = 'red', label = f'sma-{b}')\nax.plot(df.ta.sma(c), color = 'purple', label = f'sma-{c}')\n\n# signals\nxcoords_buy, xcoords_sell = golden[golden.TS_Entries == True].index, golden[golden.TS_Exits == True].index\n\nfor xc in xcoords_sell:\n plt.axvline(x=xc,c='r')\nfor xc in xcoords_buy:\n plt.axvline(x=xc,c='g')\n\n# plot outputs\nax.legend(loc = 'upper left')\nplt.show()","metadata":{"trusted":true,"execution":{"execution_failed":"2025-01-01T06:32:46.755Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# not very definitive of the absolute BEST combination. but it does yield some pretty neat outputs.","metadata":{"execution":{"execution_failed":"2025-01-01T06:32:46.755Z"},"trusted":true},"outputs":[],"execution_count":null}]}
--------------------------------------------------------------------------------
/Advanced Python Trade Techniques:
--------------------------------------------------------------------------------
1 | {"metadata":{"kernelspec":{"name":"","display_name":""},"language_info":{"name":""}},"nbformat_minor":5,"nbformat":4,"cells":[{"source":"
","metadata":{},"cell_type":"markdown"},{"id":"588f2afa","cell_type":"markdown","source":"# **Advanced Cryptocurrency Trading System**\n\n## **Introduction**\nWelcome to the most comprehensive trading system designed to maximize profits using AI, ML, and automated trading with Binance API.\n\nThis notebook covers:\n- Market analysis with `pandas_ta`\n- Reinforcement learning strategies\n- Real-time automated trade execution\n- Risk management and financial planning\n\nLet's dive into building an efficient, modern, and high-tech trading ecosystem.","metadata":{}},{"id":"11acc573","cell_type":"markdown","source":"## **1. Install Required Libraries**\n\nBefore proceeding, ensure the following packages are installed:\n\n```python\n!pip install pandas pandas_ta numpy requests binance stable-baselines3 plotly scikit-learn talib\n```","metadata":{}},{"id":"85806a7c","cell_type":"code","source":"import pandas as pd\nimport pandas_ta as ta\nimport numpy as np\nimport requests\nimport time\nimport plotly.graph_objects as go\nfrom binance.client import Client\nfrom binance.enums import *\nfrom stable_baselines3 import PPO\nfrom gym import spaces\nimport logging\nimport os\n\n# Setup logging\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')\n\n# Load API keys\nAPI_KEY = os.getenv('BINANCE_API_KEY', 'your_api_key_here')\nAPI_SECRET = os.getenv('BINANCE_API_SECRET', 'your_api_secret_here')\n\nclient = Client(API_KEY, API_SECRET)","metadata":{},"outputs":[],"execution_count":null},{"id":"0858a8db","cell_type":"markdown","source":"## **2. Data Retrieval and Preprocessing**\n\nFetching historical cryptocurrency data is a crucial step. We'll retrieve and preprocess data from Binance.\n\n### Function to Retrieve Market Data","metadata":{}},{"id":"1e6a67f6","cell_type":"code","source":"def get_binance_data(symbol=\"BTCUSDT\", interval=Client.KLINE_INTERVAL_1HOUR, lookback=\"30 day ago UTC\"):\n \"\"\"Retrieve historical data from Binance and preprocess\"\"\"\n logging.info(f\"Fetching data for {symbol} at {interval}\")\n klines = client.get_historical_klines(symbol, interval, lookback)\n\n df = pd.DataFrame(klines, columns=[\n \"timestamp\", \"open\", \"high\", \"low\", \"close\", \"volume\",\n \"close_time\", \"quote_asset_volume\", \"number_of_trades\",\n \"taker_buy_base_vol\", \"taker_buy_quote_vol\", \"ignore\"\n ])\n\n df[\"timestamp\"] = pd.to_datetime(df[\"timestamp\"], unit=\"ms\")\n df.set_index(\"timestamp\", inplace=True)\n df = df[[\"open\", \"high\", \"low\", \"close\", \"volume\"]].astype(float)\n return df\n\ndf = get_binance_data()\ndf.head()","metadata":{},"outputs":[],"execution_count":null},{"id":"9f190310","cell_type":"markdown","source":"## **3. Advanced Technical Analysis**\n\nWe'll apply a robust set of technical indicators using `pandas_ta` to enhance our analysis.","metadata":{}},{"id":"2886366b","cell_type":"code","source":"def analyze_market(df):\n df.ta.strategy(\"All\") # Apply all available indicators\n df.dropna(inplace=True)\n return df\n\ndf = analyze_market(df)\ndf.tail()","metadata":{},"outputs":[],"execution_count":null},{"id":"a6ca7428","cell_type":"markdown","source":"## **4. AI-Based Trading with Reinforcement Learning**\n\nWe implement reinforcement learning to make data-driven trading decisions.\n\n### Defining the Trading Environment","metadata":{}},{"id":"d8117dc6","cell_type":"code","source":"class CryptoTradingEnv:\n def __init__(self, df):\n self.df = df\n self.current_step = 0\n self.action_space = spaces.Discrete(3) # 0 = Hold, 1 = Buy, 2 = Sell\n self.observation_space = spaces.Box(low=0, high=1, shape=(df.shape[1],), dtype=np.float32)\n\n def reset(self):\n self.current_step = 0\n return self.df.iloc[self.current_step].values\n\n def step(self, action):\n self.current_step += 1\n reward = self.calculate_reward(action)\n done = self.current_step >= len(self.df) - 1\n return self.df.iloc[self.current_step].values, reward, done, {}\n\n def calculate_reward(self, action):\n if action == 1: # Buy\n return self.df.iloc[self.current_step][\"close\"] - self.df.iloc[self.current_step - 1][\"close\"]\n elif action == 2: # Sell\n return self.df.iloc[self.current_step - 1][\"close\"] - self.df.iloc[self.current_step][\"close\"]\n else:\n return 0\n\nenv = CryptoTradingEnv(df)\nmodel = PPO(\"MlpPolicy\", env, verbose=1)\nmodel.learn(total_timesteps=10000)","metadata":{},"outputs":[],"execution_count":null}]}
--------------------------------------------------------------------------------
/BTC - EMA-23 - Kalman:
--------------------------------------------------------------------------------
1 | {"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[],"dockerImageVersionId":30822,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"source":"
","metadata":{},"cell_type":"markdown"},{"cell_type":"markdown","source":"# Bitcoin, EMA-23, and Kalman Filter\n### By ΔΦ\n\n- save script below.py\n- open terminal\n- locate below.py\n> python below.py\n\n\n## [@donutz.ai](www.donutz.ai/#)","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2025-01-05T23:32:11.417177Z","iopub.execute_input":"2025-01-05T23:32:11.417554Z","iopub.status.idle":"2025-01-05T23:32:15.537838Z","shell.execute_reply.started":"2025-01-05T23:32:11.41751Z","shell.execute_reply":"2025-01-05T23:32:15.53641Z"}}},{"cell_type":"code","source":"from IPython.display import clear_output\n!pip install numpy pandas matplotlib filterpy plotly chart-studio\nclear_output()\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom filterpy.kalman import KalmanFilter\nfrom datetime import datetime, timedelta\nimport plotly.plotly as py\nimport plotly.graph_objs as go\nimport plotly.offline as pyoff\nfrom chart_studio import plotly\nfrom plotly import tools\nfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot\ninit_notebook_mode(connected=True) \n\n# Generate dummy Bitcoin price data (you can replace this with live data)\nnp.random.seed(42)\ndates = pd.date_range(start=datetime.now() - timedelta(days=50), periods=50).strftime('%Y-%m-%d')\nprice = np.random.normal(loc=50000, scale=3000, size=50) # Simulate Bitcoin price data\n\n# Convert data to a pandas DataFrame\ndata = pd.DataFrame({'Date': dates, 'Price': price})\ndata['Date'] = pd.to_datetime(data['Date'])\n\n# --- Step 1: Calculate Exponential Moving Average (EMA-23) ---\ndef calculate_ema(data, window=23):\n return data['Price'].ewm(span=window, adjust=False).mean()\n\ndata['EMA_23'] = calculate_ema(data)\n\n# --- Step 2: Kalman Filter ---\ndef apply_kalman_filter(data):\n # Define the Kalman filter\n kf = KalmanFilter(dim_x=1, dim_z=1)\n kf.x = np.array([data['Price'][0]]) # initial state estimate\n kf.P *= 1000. # initial uncertainty\n kf.F = np.array([[1]]) # state transition matrix\n kf.H = np.array([[1]]) # observation matrix\n kf.R = np.array([[5]]) # measurement noise\n kf.Q = np.array([[0.01]]) # process noise\n\n kalman_filtered = []\n \n for price in data['Price']:\n kf.predict()\n kf.update(price)\n kalman_filtered.append(kf.x[0])\n \n return kalman_filtered\n\ndata['Kalman_Filtered'] = apply_kalman_filter(data)\n\n# --- Step 3: Interactive Plot (Plotly) ---\nfig = go.Figure()\n\n# Bitcoin Price Line\nfig.add_trace(go.Scatter(x=data['Date'], y=data['Price'], mode='lines', name='Bitcoin Price', line=dict(color='lightblue', width=2)))\n\n# EMA-23 Line\nfig.add_trace(go.Scatter(x=data['Date'], y=data['EMA_23'], mode='lines', name='EMA-23', line=dict(color='orange', width=2, dash='dash')))\n\n# Kalman Filtered Line\nfig.add_trace(go.Scatter(x=data['Date'], y=data['Kalman_Filtered'], mode='lines', name='Kalman Filtered', line=dict(color='lightgreen', width=2, dash='dot')))\n\n# Layout\nfig.update_layout(\n title=\"Bitcoin Price, EMA-23 & Kalman Filter\",\n xaxis_title=\"Date\",\n yaxis_title=\"Price in USD\",\n template=\"plotly_dark\",\n xaxis_rangeslider_visible=True\n)\nfig.show()\n\n# --- Step 4: Display the last Bitcoin price ---\nprint(f\"Last recorded Bitcoin price: ${data['Price'].iloc[-1]:.2f}\")\nprint(f\"EMA-23 for last price: ${data['EMA_23'].iloc[-1]:.2f}\")\nprint(f\"Kalman Filter Estimate for last price: ${data['Kalman_Filtered'].iloc[-1]:.2f}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-06T08:49:22.213511Z","iopub.execute_input":"2025-01-06T08:49:22.213813Z","iopub.status.idle":"2025-01-06T08:49:32.455563Z","shell.execute_reply.started":"2025-01-06T08:49:22.213782Z","shell.execute_reply":"2025-01-06T08:49:32.453877Z"}},"outputs":[{"traceback":["\u001b[0;31m---------------------------------------------------------------------------\u001b[0m","\u001b[0;31mImportError\u001b[0m Traceback (most recent call last)","\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 7\u001b[0m \u001b[0;32mfrom\u001b[0m \u001b[0mfilterpy\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mkalman\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mKalmanFilter\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 8\u001b[0m \u001b[0;32mfrom\u001b[0m \u001b[0mdatetime\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mdatetime\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mtimedelta\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 9\u001b[0;31m \u001b[0;32mimport\u001b[0m \u001b[0mplotly\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mplotly\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0mpy\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 10\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mplotly\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mgraph_objs\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0mgo\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 11\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mplotly\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0moffline\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0mpyoff\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n","\u001b[0;32m/usr/local/lib/python3.10/dist-packages/plotly/plotly/__init__.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mfrom\u001b[0m \u001b[0m_plotly_future_\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0m_chart_studio_error\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0m_chart_studio_error\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"plotly\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m","\u001b[0;32m/usr/local/lib/python3.10/dist-packages/_plotly_future_/__init__.py\u001b[0m in \u001b[0;36m_chart_studio_error\u001b[0;34m(submodule)\u001b[0m\n\u001b[1;32m 41\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 42\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0m_chart_studio_error\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0msubmodule\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 43\u001b[0;31m raise ImportError(\n\u001b[0m\u001b[1;32m 44\u001b[0m \"\"\"\n\u001b[1;32m 45\u001b[0m \u001b[0mThe\u001b[0m \u001b[0mplotly\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0;34m{\u001b[0m\u001b[0msubmodule\u001b[0m\u001b[0;34m}\u001b[0m \u001b[0mmodule\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0mdeprecated\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n","\u001b[0;31mImportError\u001b[0m: \nThe plotly.plotly module is deprecated,\nplease install the chart-studio package and use the\nchart_studio.plotly module instead. \n"],"ename":"ImportError","evalue":"\nThe plotly.plotly module is deprecated,\nplease install the chart-studio package and use the\nchart_studio.plotly module instead. \n","output_type":"error"}],"execution_count":1},{"cell_type":"code","source":"# en fin","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}
--------------------------------------------------------------------------------
/Binance Trading Bot/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DaScient/SuperTrendTradingBot/f8070baa52422d1d5c39b646047a305db295b873/Binance Trading Bot/.DS_Store
--------------------------------------------------------------------------------
/Binance Trading Bot/.ipynb_checkpoints/README-checkpoint.md:
--------------------------------------------------------------------------------
1 | # SuperTrendTradingBot
2 |
3 | ## Introduction to Sophie - your very own personal asset trading bot :robot:
4 |
5 | To get started, clone this repository into an easy-to-find folder on your computer. Then use the terminal, or your command prompt, to get into the cloned folder. Once in the proper directory, you can run python like so: ../Desktop/SuperTrendTradingBot/Binance_Trading_Bot/ $ python meet_sophie.py
6 |
7 | Before you go further, make sure to have conda installed on your system, as well as, the latest Python release. See the general README for more details.
8 |
9 | ## Our SuperTrend Nutshell :robot:
10 |
11 |
12 |
13 | ### Resources & Repositories Used
14 | [Part Time Larrys (hackingthemarkets)'s supertrend-crypto-bot](https://github.com/hackingthemarkets/supertrend-crypto-bot)
15 |
16 | [Part Time Larrys (hackingthemarkets)'s binance-tutorials](https://github.com/hackingthemarkets/binance-tutorials)
17 |
18 | [CCXT - BinanceUS](https://github.com/ccxt/ccxt)
19 |
20 | [Binance Full History, 2017 - 2020](https://www.kaggle.com/jorijnsmit/binance-full-history)
21 |
22 |
23 |
--------------------------------------------------------------------------------
/Binance Trading Bot/.ipynb_checkpoints/binance_bot_SAMPLE-checkpoint.py:
--------------------------------------------------------------------------------
1 | import ccxt,schedule,warnings,time,ast,config
2 | warnings.filterwarnings('ignore')
3 | from dateutil.tz import tzlocal
4 | from datetime import datetime
5 | from random import randint
6 | from random import seed
7 | import pandas as pd
8 | import numpy as np
9 | ccxt.binanceus({ 'options':{ 'adjustForTimeDifference':True}})
10 | exchange = ccxt.binanceus({
11 | "apiKey": config.BINANCE_KEY,
12 | "secret": config.BINANCE_SECRET,
13 | 'enableRateLimit': True})
14 |
15 |
16 | name = 'SAMPLE'
17 | tick = 'SHIB'
18 | ticker= tick+"/USDT"
19 | timeframe = "1m"
20 | order_size = 400000000
21 | in_position = True
22 | min_sell_price = 0.00000704
23 | prev_purch_price =min_sell_price
24 | perc = 2
25 | markup = 1+perc/100
26 | max_loss = 0.1/100
27 | volatility = 0.454545454545454545454545545454545
28 |
29 | # randomizer for schedule. I know it's weird, but somehow it works nicely for me.
30 | #Feel free to remove randint(a,b) downstairs, and just let schedule(a).minutes..
31 | if timeframe == "1m":
32 | a = 55
33 | b = 60
34 | if timeframe == "5m":
35 | a = 275
36 | b = 300
37 | if timeframe == "15m":
38 | a = 850
39 | b = 900
40 | if timeframe == "30m":
41 | a = 1775
42 | b = 1800
43 | if timeframe == "1h":
44 | a = 3575
45 | b = 3600
46 |
47 | # Supertrend
48 | # (TR) The true range indicator is taken as the greatest of the following: current high less the current low; the absolute value of the current high less the previous close; and the absolute value of the current low less the previous close
49 | def tr(data):
50 | data['previous_close'] = data['close'].shift(1)
51 | data['high-low'] = abs(data['high'] - data['low'])
52 | data['high-pc'] = abs(data['high'] - data['previous_close'])
53 | data['low-pc'] = abs(data['low'] - data['previous_close'])
54 | tr = data[['high-low','high-pc','low-pc']].max(axis=1)
55 | return tr
56 |
57 | #TR rolling average
58 | def atr(data, period):
59 | data['tr'] = tr(data)
60 | atr = data['tr'].rolling(period).mean()
61 | return atr
62 |
63 | # https://www.tradingfuel.com/supertrend-indicator-formula-and-calculation/ #It's important to treat the atr_multiplier as a variable. See supertrend_visualizer_parquet.py to see how atr_mult affects indication. Volatility rate varies from 0.0001 - 3. Smaller numbers for 1m intervals. Larger number for day or swing trades.
64 | def supertrend(df, period = 7, atr_multiplier = volatility):
65 | hl2 = (df['high'] + df['low'])/2
66 | df['atr'] = atr(df, period)
67 | df['upperband'] = hl2 + (atr_multiplier * df['atr'])
68 | df['lowerband'] = hl2 - (atr_multiplier * df['atr'])
69 | df['in_uptrend'] = True
70 | for current in range(1, len(df.index)):
71 | previous = current - 1
72 | if df['close'][current] > df['upperband'][previous]:
73 | df['in_uptrend'][current] = True
74 | elif df['close'][current] < df['lowerband'][previous]:
75 | df['in_uptrend'][current] = False
76 | else:
77 | df['in_uptrend'][current] = df['in_uptrend'][previous]
78 | if (df['in_uptrend'][current]) and (df['lowerband'][current] < df['lowerband'][previous]):
79 | df['lowerband'][current] = df['lowerband'][previous]
80 | if not df['in_uptrend'][current] and df['upperband'][current]>df['upperband'][previous]:
81 | df['upperband'][current] = df['upperband'][previous]
82 | return df
83 |
84 | # Analysis & decision making. This part could be extracted out into it's own class.
85 | def check_buy_sell_signals(df):
86 |
87 | # Establish bot parameters
88 | global in_position,ticker,timeframe,min_sell_price,markup,prev_purch_price,max_loss
89 | print("Calculating", ticker ,"data...")
90 | print(df.tail(3)[['timestamp','close','low','in_uptrend']])
91 |
92 | # extract last row for df
93 | last_row_index = len(df.index) - 1
94 | previous_row_index = last_row_index - 1
95 |
96 | # check for uptrend - if in_uptrend goes from False to True
97 | if not df['in_uptrend'][previous_row_index] and df['in_uptrend'][last_row_index]:
98 | print("Changed to uptrend - Buy.")
99 |
100 | # enter position when in_uptrend True
101 | if not in_position:
102 |
103 | # send binance buy order
104 | order = exchange.create_market_buy_order(f'{ticker}', order_size)
105 |
106 | print('\nStatus:' + order['info']['status'],
107 | 'Price:' + order['trades'][0]['info']['price'],
108 | 'Quantity:' + order['info']['executedQty'],
109 | 'Type:' + order['info']['side'])
110 |
111 | # holding onto this in order to ensure bot only executes above value(1-max_loss)
112 | min_sell_price = float(order['trades'][0]['info']['price'])
113 | # i really just did a second one until i can figure out the fetch_order_by_id() fucntion.
114 | prev_purch_price = float(order['trades'][0]['info']['price'])
115 |
116 | # we are now in_position
117 | in_position = True
118 | print("Purchased @ $",str(prev_purch_price))
119 | else:
120 |
121 | # otherwise
122 | print("Already in trading position.")
123 | if prev_purch_price == min_sell_price:
124 | pass
125 | else:
126 | print("Previous purchase price: ", prev_purch_price)
127 |
128 | # check for downtrend - if in_uptrend goes from True to False
129 | if df['in_uptrend'][previous_row_index] and not df['in_uptrend'][last_row_index]:
130 | print("Changed to downtrend - Sell.")
131 |
132 | # current low price = df[-1:].reset_index(drop=True)['low'][0]
133 | price = df[-1:].reset_index(drop=True)['low'][0]
134 |
135 | # only sells if price is greater than (min_sell_price)*(markup)*(max_loss)
136 | if in_position and (min_sell_price*(1+max_loss) df['upperband'][previous]:
36 | df['in_uptrend'][current] = True
37 | elif df['close'][current] < df['lowerband'][previous]:
38 | df['in_uptrend'][current] = False
39 | else:
40 | df['in_uptrend'][current] = df['in_uptrend'][previous]
41 | if df['in_uptrend'][current] and df['lowerband'][current] < df['lowerband'][previous]:
42 | df['lowerband'][current] = df['lowerband'][previous]
43 | if not df['in_uptrend'][current] and df['upperband'][current] > df['upperband'][previous]:
44 | df['upperband'][current] = df['upperband'][previous]
45 | return df
46 |
47 | #Instance parameters
48 | name=input("Enter name: ")
49 | tick=input("Insert ticker: ")
50 | ticker=tick+"/"+input("USD or USDT?")
51 | timeframe="5m" #1m,5m,15m,30m,1h,2h,6h,1d
52 | order_size = float(input("Order size in "+tick+": "))
53 | in_position = ast.literal_eval(input("Do not accumulate until next buy signal? - True/False: ").capitalize())
54 | min_sell_price=float(input("Minimum sell price: "))
55 | perc=float(input("Enter percentage of desired markup: "+"%"))
56 | markup=1+perc/100
57 |
58 | #Analysis & decision making
59 | def check_buy_sell_signals(df):
60 | global in_position,order_size,ticker,timeframe,trade_amount,min_sell_price,markup
61 | print("Analyzing",ticker,"data... \n")
62 | print(df.tail(3)[['timestamp','close','volume','in_uptrend']])
63 | last_row_index = len(df.index) - 1
64 | previous_row_index = last_row_index - 1
65 | if not df['in_uptrend'][previous_row_index] and df['in_uptrend'][last_row_index]:
66 | print("Changed to uptrend. Attempting purchase.")
67 | if not in_position:
68 | order = exchange.create_market_buy_order(f'{ticker}',order_size)
69 | print('\nStatus:'+order['info']['status'],
70 | 'Price:'+order['trades'][0]['info']['price'],
71 | 'Quantity:'+order['info']['executedQty'],
72 | 'Type:'+order['info']['side'])
73 | min_sell_price = float(order['trades'][0]['info']['price'])*markup
74 | in_position = True
75 | print("Purchased @ $",str(min_sell_price))
76 | else:
77 | print("Already in desired trading position, no task.")
78 | if df['in_uptrend'][previous_row_index] and not df['in_uptrend'][last_row_index]:
79 | bar = exchange.fetch_ohlcv(f'{ticker}', timeframe="1m", limit=1)
80 | price = float(bar[-1][3]) #identifies current low price
81 | print("Changed to downtrend. Attempting sale.")
82 | if in_position and price > min_sell_price:
83 | order = exchange.create_market_sell_order(f'{ticker}',order_size)
84 | print('Status:'+order['info']['status'],
85 | 'Price:'+order['trades'][0]['info']['price'],
86 | 'Quantity:'+order['info']['executedQty'],
87 | 'Type:'+order['info']['side'])
88 | in_position = False
89 | print('Sold @',str(order['trades'][0]['info']['price']),', Loss/gain ',str(1-float(1-order['trades'][0]['info']['price'])/min_sell_price),'%.')
90 | else:
91 | print("Did not find an opportunity to sell, no task.")
92 |
93 | def run_bot():
94 | print(f"\nFetching new bars for {datetime.now(tzlocal()).isoformat()}")
95 | print("In position:", in_position,";\nTimeframe: ",timeframe,"\n")
96 | bars = exchange.fetch_ohlcv(f'{ticker}', timeframe=timeframe, limit=100)
97 | df = pd.DataFrame(bars[:-1], columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
98 | df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms').dt.tz_localize(None)
99 | supertrend_data = supertrend(df)
100 | check_buy_sell_signals(supertrend_data,in_position,order_size,ticker,timeframe,min_sell_price,markup)
101 | bal = pd.DataFrame(exchange.fetch_balance()['info']['balances'])
102 | bal['free'] = pd.to_numeric(bal['free'])
103 | bal = bal[bal.free!=0].drop(columns='locked').reset_index(drop=True)
104 | bal = bal[bal['asset']==ticker[:4].replace('/','')].reset_index(drop=True).free[0]
105 | print("\nBalance: $",bal*bars[-1][1],", Position:",bal)
106 | print("Minimum sell price:",min_sell_price,", Order size:",order_size)
107 | print(name,"'s Markup set to:",markup,"%")
108 | schedule.every(randint(800,900)).seconds.do(run_bot)
109 | while True:
110 | schedule.run_pending()
111 | time.sleep(1)
--------------------------------------------------------------------------------
/Binance Trading Bot/.ipynb_checkpoints/config-checkpoint.py:
--------------------------------------------------------------------------------
1 | #KEEP ULTRA SAFE
2 |
3 | from random import seed
4 | from random import randint
5 |
6 | random.seed(10)
7 |
8 | # main
9 | BINANCE_KEY=""
10 | BINANCE_SECRET=""
11 |
12 | # overclocking mitigation.
13 | # create multiple API Instances and have them random loop through class below.
14 | # binance - Can you make these juggle?
15 | BINANCE_KEY_v1=""
16 | BINANCE_SECRET_v1=""
17 |
18 | BINANCE_KEY_v2=""
19 | BINANCE_SECRET_v2=""
20 |
21 | BINANCE_KEY_v3=""
22 | BINANCE_SECRET_v3=""
23 |
24 |
25 | BINANCE_KEY_v4=""
26 | BINANCE_SECRET_v4=""
27 |
28 | # unrestricted
29 | BINANCE_KEY_v5=""
30 | BINANCE_SECRET_v5=""
31 |
32 | BINANCE_KEY_v6=""
33 | BINANCE_SECRET_v6=""
34 |
35 | BINANCE_KEY_v7=""
36 | BINANCE_SECRET_v7=""
37 |
38 |
39 | # robinhood
40 | rh_username = ""
41 | rh_password = ""
42 |
43 |
--------------------------------------------------------------------------------
/Binance Trading Bot/.ipynb_checkpoints/get_balance-checkpoint.py:
--------------------------------------------------------------------------------
1 | #Unpack necessities
2 | import my_config,schedule,time,csv,ccxt
3 | from dateutil.tz import tzlocal
4 | from datetime import datetime
5 | import pandas as pd
6 | import numpy as np
7 | import warnings
8 | warnings.filterwarnings('ignore')
9 |
10 | # login
11 | ccxt.binanceus({ 'options':{ 'adjustForTimeDifference':True}})
12 |
13 | # {random key generator}
14 | # for reference see config.py
15 | value = randint(2,199)
16 | print(f"\n\nRandomized KeyPair Identification: {value}\n\n...")
17 | if 1 < value <= 25:
18 | key = config.BINANCE_KEY_v7
19 | secret = config.BINANCE_SECRET_v7
20 |
21 | if 25 < value <= 50:
22 | key = config.BINANCE_KEY_v6
23 | secret = config.BINANCE_SECRET_v6
24 |
25 | if 50 < value <= 75:
26 | key = config.BINANCE_KEY_v5
27 | secret = config.BINANCE_SECRET_v5
28 |
29 | if 75 < value <= 100:
30 | key = config.BINANCE_KEY_v4
31 | secret = config.BINANCE_SECRET_v4
32 |
33 | if 100 < value <= 125:
34 | key = config.BINANCE_KEY_v3
35 | secret = config.BINANCE_SECRET_v3
36 |
37 | if 125 < value <= 150:
38 | key = config.BINANCE_KEY_v2
39 | secret = config.BINANCE_SECRET_v2
40 |
41 | if 150 < value <= 175:
42 | key = config.BINANCE_KEY_v1
43 | secret = config.BINANCE_SECRET_v1
44 |
45 | if 175 < value <= 200:
46 | key = config.BINANCE_KEY_v0
47 | secret = config.BINANCE_SECRET_v0
48 | # {end of random key generator}
49 |
50 | exchange = ccxt.binanceus({"apiKey": key, "secret": secret, "enableRateLimit": True})
51 |
52 | #Get USD balance data
53 | bal = pd.DataFrame(exchange.fetch_balance()['info']['balances'])
54 | bal['free'] = pd.to_numeric(bal['free'])
55 | bal = bal[bal.free!=0].drop(columns='locked').reset_index(drop=True)
56 | bal = bal.sort_values('free',ascending=False).reset_index(drop=True)
57 | bal = bal[bal.free>1]
58 |
59 | assets=[]
60 | for index,asset in bal.asset.items():
61 | try:
62 | info = exchange.fetch_ohlcv(str(asset+'/USD'), timeframe="1m", limit=1)
63 | assets.append({'asset':asset,'balance':bal.free[index],
64 | 'price':info[0][1],'balance_usd':bal.free[index]*info[0][1],
65 | 'trade_amount':int(bal.free[index]*info[0][1]-bal.free[index]*info[0][1]*.16),
66 | 'order_size':int(bal.free[index]*info[0][1]-bal.free[index]*info[0][1]*.16)/info[0][1]})
67 | except:
68 | pass
69 |
70 | df = pd.DataFrame(assets).sort_values('balance_usd',ascending=False).reset_index(drop=True)
71 | df = df[df.order_size>0]
72 |
73 | print("\nUSD Wallet\n",df,"\nUSD Total balance:",df.balance_usd.sum())
74 |
75 | ############################################################################################################
76 |
77 | #Get USDT balance data
78 | bal = pd.DataFrame(exchange.fetch_balance()['info']['balances'])
79 | bal['free'] = pd.to_numeric(bal['free'])
80 | bal = bal[bal.free!=0].drop(columns='locked').reset_index(drop=True)
81 | bal = bal.sort_values('free',ascending=False).reset_index(drop=True)
82 | bal = bal[bal.free>0]
83 |
84 | assets=[]
85 | for index,asset in bal.asset.items():
86 | try:
87 | info = exchange.fetch_ohlcv(str(asset+'/USDT'), timeframe="1m", limit=1)
88 | assets.append({'asset':asset,'balance':bal.free[index],
89 | 'price':info[0][1],'balance_usd':bal.free[index]*info[0][1],
90 | 'trade_amount':int(bal.free[index]*info[0][1]-bal.free[index]*info[0][1]*.16),
91 | 'order_size':int(bal.free[index]*info[0][1]-bal.free[index]*info[0][1]*.16)/info[0][1]})
92 | except:
93 | pass
94 | df = pd.DataFrame(assets).sort_values('balance_usd',ascending=False).reset_index(drop=True)
95 | df = df[df.order_size>0]
96 | print("\nUSDT Wallet\n",df,"\nUSDT Total balance:",df.balance_usd.sum())
97 |
98 | ############################################################################################################
99 |
100 | #Get user balance data
101 | acct = pd.DataFrame(exchange.fetch_balance()['info']['balances'], columns=['asset','free'])
102 | acct['balance'] = pd.to_numeric(acct.free)
103 | acct = acct[acct.balance > 0].drop(columns=['free'])
104 | acct = acct.sort_values(by = ['balance'], ascending = False).reset_index(drop = True)
105 | #acct
106 |
107 | # fetch tradeable balance
108 | assets = []
109 | for index,asset in acct.asset.items():
110 | #print(index,asset)
111 | try:
112 | info = exchange.fetch_ohlcv(str(asset+'/USDT'), timeframe="1m", limit=1)
113 | assets.append({'asset' : asset, 'balance': acct.balance[index],'price': info[0][1],
114 | 'sugg_trade_amt': float(acct.balance[index]*info[0][1] * (0.85)/info[0][1])})
115 | except:
116 | pass
117 | assets = pd.DataFrame(assets)
118 | assets = assets[assets.sugg_trade_amt > 0.5]
119 | print("\n User tradeable balance.")
120 | print(assets)
--------------------------------------------------------------------------------
/Binance Trading Bot/.ipynb_checkpoints/marquee-checkpoint.py:
--------------------------------------------------------------------------------
1 | import ccxt,schedule,warnings,time,ast,config
2 | warnings.filterwarnings('ignore')
3 | from dateutil.tz import tzlocal
4 | from datetime import datetime
5 | from random import randint
6 | from random import seed
7 | import pandas as pd
8 | import numpy as np
9 |
10 | ccxt.binanceus({ 'options':{ 'adjustForTimeDifference':True}})
11 | exchange = ccxt.binanceus({
12 | "apiKey": config.BINANCE_KEY,
13 | "secret": config.BINANCE_SECRET,
14 | 'enableRateLimit': True})
15 |
16 | # params
17 | tick=input("Insert ticker: ")
18 | ticker=tick+"/"+input("USD or USDT? ")
19 | timeframe = input("Enter desired candlestick intervals, 1m,5m,15m,1h,1d: ")
20 | volatility=float(input("Volatility rate (example: 0.55555 for short-term volatility, 3 for long-term volatility.): "))
21 |
22 | # Randomizer for schedule. I know it's weird, but somehow it works nicely for me.
23 | #Feel free to remove randint(a,b) downstairs, and just let schedule(a).minutes..
24 | if timeframe == "1m":
25 | a = 55
26 | b = 60
27 | if timeframe == "5m":
28 | a = 275
29 | b = 300
30 | if timeframe == "15m":
31 | a = 850
32 | b = 900
33 | if timeframe == "30m":
34 | a = 1775
35 | b = 1800
36 | if timeframe == "1h":
37 | a = 3575
38 | b = 3600
39 |
40 | # Supertrend
41 | # (TR) The true range indicator is taken as the greatest of the following: current high less the current low; the absolute value of the current high less the previous close; and the absolute value of the current low less the previous close
42 | def tr(data):
43 | data['previous_close'] = data['close'].shift(1)
44 | data['high-low'] = abs(data['high'] - data['low'])
45 | data['high-pc'] = abs(data['high'] - data['previous_close'])
46 | data['low-pc'] = abs(data['low'] - data['previous_close'])
47 | tr = data[['high-low','high-pc','low-pc']].max(axis=1)
48 | return tr
49 |
50 | #TR rolling average
51 | def atr(data, period):
52 | data['tr'] = tr(data)
53 | atr = data['tr'].rolling(period).mean()
54 | return atr
55 |
56 | # https://www.tradingfuel.com/supertrend-indicator-formula-and-calculation/ #It's important to treat the atr_multiplier as a variable. See supertrend_visualizer_parquet.py to see how atr_mult affects indication. Volatility rate varies from 0.0001 - 3. Smaller numbers for 1m intervals. Larger number for day or swing trades.
57 | def supertrend(df, period = 7, atr_multiplier = volatility):
58 | hl2 = (df['high'] + df['low'])/2
59 | df['atr'] = atr(df, period)
60 | df['upperband'] = hl2 + (atr_multiplier * df['atr'])
61 | df['lowerband'] = hl2 - (atr_multiplier * df['atr'])
62 | df['in_uptrend'] = True
63 | for current in range(1, len(df.index)):
64 | previous = current - 1
65 | if df['close'][current] > df['upperband'][previous]:
66 | df['in_uptrend'][current] = True
67 | elif df['close'][current] < df['lowerband'][previous]:
68 | df['in_uptrend'][current] = False
69 | else:
70 | df['in_uptrend'][current] = df['in_uptrend'][previous]
71 | if (df['in_uptrend'][current]) and (df['lowerband'][current] < df['lowerband'][previous]):
72 | df['lowerband'][current] = df['lowerband'][previous]
73 | if not df['in_uptrend'][current] and df['upperband'][current] > df['upperband'][previous]:
74 | df['upperband'][current] = df['upperband'][previous]
75 | return df
76 |
77 | # Analysis & decision making. This part could be extracted out into it's own class.
78 | def check_buy_sell_signals(df):
79 |
80 | # Establish bot parameters
81 | global ticker,timeframe
82 | print("Calculating", ticker ,"data...")
83 | print(df.tail(3)[['timestamp','close','low','volume','in_uptrend']])
84 |
85 | # extract last row for df
86 | last_row_index = len(df.index) - 1
87 | previous_row_index = last_row_index - 1
88 |
89 | # check for uptrend - if in_uptrend goes from False to True
90 | if not df['in_uptrend'][previous_row_index] and df['in_uptrend'][last_row_index]:
91 |
92 | # no executions, just signals.
93 | print("\n############################")
94 | print("# Changed to uptrend - Buy #")
95 | print("############################")
96 |
97 | # check for downtrend - if in_uptrend goes from True to False
98 | if df['in_uptrend'][previous_row_index] and not df['in_uptrend'][last_row_index]:
99 |
100 | # no executions, just signals.
101 | print("\n###############################")
102 | print("# Changed to downtrend - Sell #")
103 | print("###############################")
104 |
105 | # run
106 | def run_bot():
107 | print(f"\n{datetime.now(tzlocal()).isoformat()}")
108 | print("\tTimeframe:",timeframe,"\n")
109 |
110 | # pulls in df to be used for calculations
111 | bars = exchange.fetch_ohlcv(f'{ticker}', timeframe=timeframe, limit=50)
112 | df = pd.DataFrame(bars[:-1], columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
113 | df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms').dt.tz_localize(None)
114 |
115 | supertrend_data = supertrend(df)
116 | check_buy_sell_signals(supertrend_data)
117 |
118 | """
119 | Run Bot, To the Moon
120 | """
121 | schedule.every(randint(a,b)).seconds.do(run_bot)
122 | while True:
123 | schedule.run_pending()
124 | time.sleep(0)
--------------------------------------------------------------------------------
/Binance Trading Bot/.ipynb_checkpoints/remove_this_prefix_after_configured_config-checkpoint.py:
--------------------------------------------------------------------------------
1 | #KEEP ULTRA SAFE
2 |
3 | from random import seed
4 | from random import randint
5 |
6 | BINANCE_KEY=""
7 | BINANCE_SECRET=""
8 |
9 | #Overclocking mitigation
10 | #Create multiple API Instances and have them random loop through class below.
11 | #Still needs development.
12 | value = randint(0, 25)
13 | if value < 5:
14 | BINANCE_KEY=""
15 | BINANCE_SECRET=""
16 | if 6 <= value <= 10:
17 | BINANCE_KEY=""
18 | BINANCE_SECRET=""
19 | if 11 <= value <= 15:
20 | BINANCE_KEY=""
21 | BINANCE_SECRET=""
22 | if 16 <= value <= 20:
23 | BINANCE_KEY=""
24 | BINANCE_SECRET=""
25 | if 21 <= value <= 25:
26 | BINANCE_KEY=""
27 | BINANCE_SECRET=""
28 |
29 | #Robinhood
30 | rh_username = ""
31 | rh_password = ""
32 |
33 |
--------------------------------------------------------------------------------
/Binance Trading Bot/.ipynb_checkpoints/requirements-checkpoint.txt:
--------------------------------------------------------------------------------
1 | ccxt
2 | parquet
3 | rich
--------------------------------------------------------------------------------
/Binance Trading Bot/.ipynb_checkpoints/supertrend_atr_multiplier_test-checkpoint.py:
--------------------------------------------------------------------------------
1 | #Importation
2 | import ccxt,schedule,warnings,time,ast
3 | warnings.filterwarnings('ignore')
4 | import matplotlib.pyplot as plt
5 | from dateutil.tz import tzlocal
6 | from datetime import datetime
7 | import seaborn as sns
8 | from PIL import Image
9 | import pandas as pd
10 | import numpy as np
11 |
12 | #Set user variables
13 | tick=input("Insert ticker: ")
14 | ticker=tick+"/"+input("USD or USDT?")
15 | timeframe=input("Insert desired time intervals: ")
16 | period=int(input("Period window: "))
17 | volatility=float(input("Volatility rate: "))
18 | limit_frame=int(input("Input 50-50000: "))
19 |
20 | df=exchange.fetch_ohlcv(f'{ticker}', timeframe=timeframe, limit=limit)
21 | df = pd.DataFrame(df[:-1], columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
22 | df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms').dt.tz_localize(None)
23 |
24 | #Supertrend
25 | def tr(data):
26 | data['previous_close']=data['close'].shift(1)
27 | data['high-low']=abs(data['high']-data['low'])
28 | data['high-pc']=abs(data['high']-data['previous_close'])
29 | data['low-pc']=abs(data['low']-data['previous_close'])
30 | tr=data[['high-low','high-pc','low-pc']].max(axis=1)
31 | return tr
32 | def atr(data, period):
33 | data['tr']=tr(data)
34 | atr=data['tr'].rolling(period).mean()
35 | return atr
36 | def supertrend(df,period=period,atr_multiplier=volatility):
37 | hl2=(df['high']+df['low'])/2
38 | df['atr']=atr(df, period)
39 | df['upperband']=hl2+(atr_multiplier*df['atr'])
40 | df['lowerband']=hl2-(atr_multiplier*df['atr'])
41 | df['in_uptrend']=True
42 | for current in range(1,len(df.index)):
43 | previous=current-1
44 | if df['close'][current]>df['upperband'][previous]:
45 | df['in_uptrend'][current]=True
46 | elif df['close'][current]df['upperband'][previous]:
53 | df['upperband'][current]=df['upperband'][previous]
54 | return df
55 |
56 | #Apply supertrend formula
57 | supertrend_data= supertrend(df)
58 |
59 | #Set plot() params
60 | fig, ax = plt.subplots(figsize=(20, 8))
61 |
62 | #Signals 1.1
63 | xcoords_sell = supertrend_data[supertrend_data.in_uptrend == False].index
64 | xcoords_buy = supertrend_data[supertrend_data.in_uptrend == True].index
65 |
66 | #Signals 1.2
67 | for xc in xcoords_sell:
68 | plt.axvline(x=xc,c='r')
69 | for xc in xcoords_buy:
70 | plt.axvline(x=xc,c='g')
71 |
72 | #Plot close price
73 | ax.plot(supertrend_data.close, color = 'black', label = 'Line 1')
74 |
75 | #Plot bollinger bands
76 | ax.plot(supertrend_data.upperband, color = 'lime', label = 'upperband')
77 | ax.plot(supertrend_data.lowerband, color = 'pink', label = 'lowerband')
78 |
79 | #PLot outputs
80 | ax.legend(loc = 'upper left')
81 | plt.savefig(f'supertrend_visual_{tick}_{volatility}.jpg')
82 | plt.show()
83 |
84 | #Open .jpg
85 | Image.open(f"supertrend_visual_{tick}_{volatility}.jpg")
--------------------------------------------------------------------------------
/Binance Trading Bot/README.md:
--------------------------------------------------------------------------------
1 | # SuperTrendTradingBot
2 |
3 | ## Introduction to Safemode-Enabled BinanceUS trading bot - your very own personal asset trading bot :robot:
4 |
5 | To get started, clone this repository into an easy-to-find folder on your computer.
6 |
7 | Before you go further, make sure to have conda installed on your system, as well as, the latest Python release. See the general README for more details.
8 |
9 | Use the terminal, or your command prompt, to get into the cloned folder. Once in the proper directory, you can run python like so: ../SuperTrendTradingBot/Binance_Trading_Bot/ >> python safemode_binance_bot.py
10 |
11 | ## Our SuperTrend Nutshell :robot:
12 |
13 |
14 |
15 | ### Resources & Repositories Used
16 | [Part Time Larrys (hackingthemarkets)'s supertrend-crypto-bot](https://github.com/hackingthemarkets/supertrend-crypto-bot)
17 |
18 | [Part Time Larrys (hackingthemarkets)'s binance-tutorials](https://github.com/hackingthemarkets/binance-tutorials)
19 |
20 | [CCXT - BinanceUS](https://github.com/ccxt/ccxt)
21 |
22 | [Binance Full History, 2017 - 2020](https://www.kaggle.com/jorijnsmit/binance-full-history)
23 |
24 |
25 |
--------------------------------------------------------------------------------
/Binance Trading Bot/binance_bot_SAMPLE.py:
--------------------------------------------------------------------------------
1 | import ccxt,schedule,warnings,time,ast,config
2 | warnings.filterwarnings('ignore')
3 | from dateutil.tz import tzlocal
4 | from datetime import datetime
5 | from random import randint
6 | from random import seed
7 | import pandas as pd
8 | import numpy as np
9 | ccxt.binanceus({ 'options':{ 'adjustForTimeDifference':True}})
10 | exchange = ccxt.binanceus({
11 | "apiKey": config.BINANCE_KEY,
12 | "secret": config.BINANCE_SECRET,
13 | 'enableRateLimit': True})
14 |
15 |
16 | name = 'SAMPLE'
17 | tick = 'SHIB'
18 | ticker= tick+"/USDT"
19 | timeframe = "1m"
20 | order_size = 400000000
21 | in_position = True
22 | min_sell_price = 0.00000704
23 | prev_purch_price =min_sell_price
24 | perc = 2
25 | markup = 1+perc/100
26 | max_loss = 0.1/100
27 | volatility = 0.454545454545454545454545545454545
28 |
29 | # randomizer for schedule. I know it's weird, but somehow it works nicely for me.
30 | #Feel free to remove randint(a,b) downstairs, and just let schedule(a).minutes..
31 | if timeframe == "1m":
32 | a = 55
33 | b = 60
34 | if timeframe == "5m":
35 | a = 275
36 | b = 300
37 | if timeframe == "15m":
38 | a = 850
39 | b = 900
40 | if timeframe == "30m":
41 | a = 1775
42 | b = 1800
43 | if timeframe == "1h":
44 | a = 3575
45 | b = 3600
46 |
47 | # Supertrend
48 | # (TR) The true range indicator is taken as the greatest of the following: current high less the current low; the absolute value of the current high less the previous close; and the absolute value of the current low less the previous close
49 | def tr(data):
50 | data['previous_close'] = data['close'].shift(1)
51 | data['high-low'] = abs(data['high'] - data['low'])
52 | data['high-pc'] = abs(data['high'] - data['previous_close'])
53 | data['low-pc'] = abs(data['low'] - data['previous_close'])
54 | tr = data[['high-low','high-pc','low-pc']].max(axis=1)
55 | return tr
56 |
57 | #TR rolling average
58 | def atr(data, period):
59 | data['tr'] = tr(data)
60 | atr = data['tr'].rolling(period).mean()
61 | return atr
62 |
63 | # https://www.tradingfuel.com/supertrend-indicator-formula-and-calculation/ #It's important to treat the atr_multiplier as a variable. See supertrend_visualizer_parquet.py to see how atr_mult affects indication. Volatility rate varies from 0.0001 - 3. Smaller numbers for 1m intervals. Larger number for day or swing trades.
64 | def supertrend(df, period = 7, atr_multiplier = volatility):
65 | hl2 = (df['high'] + df['low'])/2
66 | df['atr'] = atr(df, period)
67 | df['upperband'] = hl2 + (atr_multiplier * df['atr'])
68 | df['lowerband'] = hl2 - (atr_multiplier * df['atr'])
69 | df['in_uptrend'] = True
70 | for current in range(1, len(df.index)):
71 | previous = current - 1
72 | if df['close'][current] > df['upperband'][previous]:
73 | df['in_uptrend'][current] = True
74 | elif df['close'][current] < df['lowerband'][previous]:
75 | df['in_uptrend'][current] = False
76 | else:
77 | df['in_uptrend'][current] = df['in_uptrend'][previous]
78 | if (df['in_uptrend'][current]) and (df['lowerband'][current] < df['lowerband'][previous]):
79 | df['lowerband'][current] = df['lowerband'][previous]
80 | if not df['in_uptrend'][current] and df['upperband'][current]>df['upperband'][previous]:
81 | df['upperband'][current] = df['upperband'][previous]
82 | return df
83 |
84 | # Analysis & decision making. This part could be extracted out into it's own class.
85 | def check_buy_sell_signals(df):
86 |
87 | # Establish bot parameters
88 | global in_position,ticker,timeframe,min_sell_price,markup,prev_purch_price,max_loss
89 | print("Calculating", ticker ,"data...")
90 | print(df.tail(3)[['timestamp','close','low','in_uptrend']])
91 |
92 | # extract last row for df
93 | last_row_index = len(df.index) - 1
94 | previous_row_index = last_row_index - 1
95 |
96 | # check for uptrend - if in_uptrend goes from False to True
97 | if not df['in_uptrend'][previous_row_index] and df['in_uptrend'][last_row_index]:
98 | print("Changed to uptrend - Buy.")
99 |
100 | # enter position when in_uptrend True
101 | if not in_position:
102 |
103 | # send binance buy order
104 | order = exchange.create_market_buy_order(f'{ticker}', order_size)
105 |
106 | print('\nStatus:' + order['info']['status'],
107 | 'Price:' + order['trades'][0]['info']['price'],
108 | 'Quantity:' + order['info']['executedQty'],
109 | 'Type:' + order['info']['side'])
110 |
111 | # holding onto this in order to ensure bot only executes above value(1-max_loss)
112 | min_sell_price = float(order['trades'][0]['info']['price'])
113 | # i really just did a second one until i can figure out the fetch_order_by_id() fucntion.
114 | prev_purch_price = float(order['trades'][0]['info']['price'])
115 |
116 | # we are now in_position
117 | in_position = True
118 | print("Purchased @ $",str(prev_purch_price))
119 | else:
120 |
121 | # otherwise
122 | print("Already in trading position.")
123 | if prev_purch_price == min_sell_price:
124 | pass
125 | else:
126 | print("Previous purchase price: ", prev_purch_price)
127 |
128 | # check for downtrend - if in_uptrend goes from True to False
129 | if df['in_uptrend'][previous_row_index] and not df['in_uptrend'][last_row_index]:
130 | print("Changed to downtrend - Sell.")
131 |
132 | # current low price = df[-1:].reset_index(drop=True)['low'][0]
133 | price = df[-1:].reset_index(drop=True)['low'][0]
134 |
135 | # only sells if price is greater than (min_sell_price)*(markup)*(max_loss)
136 | if in_position and (min_sell_price*(1+max_loss)1]
58 |
59 | assets=[]
60 | for index,asset in bal.asset.items():
61 | try:
62 | info = exchange.fetch_ohlcv(str(asset+'/USD'), timeframe="1m", limit=1)
63 | assets.append({'asset':asset,'balance':bal.free[index],
64 | 'price':info[0][1],'balance_usd':bal.free[index]*info[0][1],
65 | 'trade_amount':int(bal.free[index]*info[0][1]-bal.free[index]*info[0][1]*.16),
66 | 'order_size':int(bal.free[index]*info[0][1]-bal.free[index]*info[0][1]*.16)/info[0][1]})
67 | except:
68 | pass
69 |
70 | df = pd.DataFrame(assets).sort_values('balance_usd',ascending=False).reset_index(drop=True)
71 | df = df[df.order_size>0]
72 |
73 | print("\nUSD Wallet\n",df,"\nUSD Total balance:",df.balance_usd.sum())
74 |
75 | ############################################################################################################
76 |
77 | #Get USDT balance data
78 | bal = pd.DataFrame(exchange.fetch_balance()['info']['balances'])
79 | bal['free'] = pd.to_numeric(bal['free'])
80 | bal = bal[bal.free!=0].drop(columns='locked').reset_index(drop=True)
81 | bal = bal.sort_values('free',ascending=False).reset_index(drop=True)
82 | bal = bal[bal.free>0]
83 |
84 | assets=[]
85 | for index,asset in bal.asset.items():
86 | try:
87 | info = exchange.fetch_ohlcv(str(asset+'/USDT'), timeframe="1m", limit=1)
88 | assets.append({'asset':asset,'balance':bal.free[index],
89 | 'price':info[0][1],'balance_usd':bal.free[index]*info[0][1],
90 | 'trade_amount':int(bal.free[index]*info[0][1]-bal.free[index]*info[0][1]*.16),
91 | 'order_size':int(bal.free[index]*info[0][1]-bal.free[index]*info[0][1]*.16)/info[0][1]})
92 | except:
93 | pass
94 | df = pd.DataFrame(assets).sort_values('balance_usd',ascending=False).reset_index(drop=True)
95 | df = df[df.order_size>0]
96 | print("\nUSDT Wallet\n",df,"\nUSDT Total balance:",df.balance_usd.sum())
97 |
98 | ############################################################################################################
99 |
100 | #Get user balance data
101 | acct = pd.DataFrame(exchange.fetch_balance()['info']['balances'], columns=['asset','free'])
102 | acct['balance'] = pd.to_numeric(acct.free)
103 | acct = acct[acct.balance > 0].drop(columns=['free'])
104 | acct = acct.sort_values(by = ['balance'], ascending = False).reset_index(drop = True)
105 | #acct
106 |
107 | # fetch tradeable balance
108 | assets = []
109 | for index,asset in acct.asset.items():
110 | #print(index,asset)
111 | try:
112 | info = exchange.fetch_ohlcv(str(asset+'/USDT'), timeframe="1m", limit=1)
113 | assets.append({'asset' : asset, 'balance': acct.balance[index],'price': info[0][1],
114 | 'sugg_trade_amt': float(acct.balance[index]*info[0][1] * (0.85)/info[0][1])})
115 | except:
116 | pass
117 | assets = pd.DataFrame(assets)
118 | assets = assets[assets.sugg_trade_amt > 0.5]
119 | print("\n User tradeable balance.")
120 | print(assets)
--------------------------------------------------------------------------------
/Binance Trading Bot/marquee.py:
--------------------------------------------------------------------------------
1 | import ccxt,schedule,warnings,time,ast,config
2 | warnings.filterwarnings('ignore')
3 | from dateutil.tz import tzlocal
4 | from datetime import datetime
5 | from random import randint
6 | from random import seed
7 | import pandas as pd
8 | import numpy as np
9 |
10 | ccxt.binanceus({ 'options':{ 'adjustForTimeDifference':True}})
11 | exchange = ccxt.binanceus({
12 | "apiKey": config.BINANCE_KEY,
13 | "secret": config.BINANCE_SECRET,
14 | 'enableRateLimit': True})
15 |
16 | # params
17 | tick=input("Insert ticker: ")
18 | ticker=tick+"/"+input("USD or USDT? ")
19 | timeframe = input("Enter desired candlestick intervals, 1m,5m,15m,1h,1d: ")
20 | volatility=float(input("Volatility rate (example: 0.55555 for short-term volatility, 3 for long-term volatility.): "))
21 |
22 | # Randomizer for schedule. I know it's weird, but somehow it works nicely for me.
23 | #Feel free to remove randint(a,b) downstairs, and just let schedule(a).minutes..
24 | if timeframe == "1m":
25 | a = 55
26 | b = 60
27 | if timeframe == "5m":
28 | a = 275
29 | b = 300
30 | if timeframe == "15m":
31 | a = 850
32 | b = 900
33 | if timeframe == "30m":
34 | a = 1775
35 | b = 1800
36 | if timeframe == "1h":
37 | a = 3575
38 | b = 3600
39 |
40 | # Supertrend
41 | # (TR) The true range indicator is taken as the greatest of the following: current high less the current low; the absolute value of the current high less the previous close; and the absolute value of the current low less the previous close
42 | def tr(data):
43 | data['previous_close'] = data['close'].shift(1)
44 | data['high-low'] = abs(data['high'] - data['low'])
45 | data['high-pc'] = abs(data['high'] - data['previous_close'])
46 | data['low-pc'] = abs(data['low'] - data['previous_close'])
47 | tr = data[['high-low','high-pc','low-pc']].max(axis=1)
48 | return tr
49 |
50 | #TR rolling average
51 | def atr(data, period):
52 | data['tr'] = tr(data)
53 | atr = data['tr'].rolling(period).mean()
54 | return atr
55 |
56 | # https://www.tradingfuel.com/supertrend-indicator-formula-and-calculation/ #It's important to treat the atr_multiplier as a variable. See supertrend_visualizer_parquet.py to see how atr_mult affects indication. Volatility rate varies from 0.0001 - 3. Smaller numbers for 1m intervals. Larger number for day or swing trades.
57 | def supertrend(df, period = 7, atr_multiplier = volatility):
58 | hl2 = (df['high'] + df['low'])/2
59 | df['atr'] = atr(df, period)
60 | df['upperband'] = hl2 + (atr_multiplier * df['atr'])
61 | df['lowerband'] = hl2 - (atr_multiplier * df['atr'])
62 | df['in_uptrend'] = True
63 | for current in range(1, len(df.index)):
64 | previous = current - 1
65 | if df['close'][current] > df['upperband'][previous]:
66 | df['in_uptrend'][current] = True
67 | elif df['close'][current] < df['lowerband'][previous]:
68 | df['in_uptrend'][current] = False
69 | else:
70 | df['in_uptrend'][current] = df['in_uptrend'][previous]
71 | if (df['in_uptrend'][current]) and (df['lowerband'][current] < df['lowerband'][previous]):
72 | df['lowerband'][current] = df['lowerband'][previous]
73 | if not df['in_uptrend'][current] and df['upperband'][current] > df['upperband'][previous]:
74 | df['upperband'][current] = df['upperband'][previous]
75 | return df
76 |
77 | # Analysis & decision making. This part could be extracted out into it's own class.
78 | def check_buy_sell_signals(df):
79 |
80 | # Establish bot parameters
81 | global ticker,timeframe
82 | print("Calculating", ticker ,"data...")
83 | print(df.tail(3)[['timestamp','close','low','volume','in_uptrend']])
84 |
85 | # extract last row for df
86 | last_row_index = len(df.index) - 1
87 | previous_row_index = last_row_index - 1
88 |
89 | # check for uptrend - if in_uptrend goes from False to True
90 | if not df['in_uptrend'][previous_row_index] and df['in_uptrend'][last_row_index]:
91 |
92 | # no executions, just signals.
93 | print("\n############################")
94 | print("# Changed to uptrend - Buy #")
95 | print("############################")
96 |
97 | # check for downtrend - if in_uptrend goes from True to False
98 | if df['in_uptrend'][previous_row_index] and not df['in_uptrend'][last_row_index]:
99 |
100 | # no executions, just signals.
101 | print("\n###############################")
102 | print("# Changed to downtrend - Sell #")
103 | print("###############################")
104 |
105 | # run
106 | def run_bot():
107 | print(f"\n{datetime.now(tzlocal()).isoformat()}")
108 | print("\tTimeframe:",timeframe,"\n")
109 |
110 | # pulls in df to be used for calculations
111 | bars = exchange.fetch_ohlcv(f'{ticker}', timeframe=timeframe, limit=50)
112 | df = pd.DataFrame(bars[:-1], columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
113 | df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms').dt.tz_localize(None)
114 |
115 | supertrend_data = supertrend(df)
116 | check_buy_sell_signals(supertrend_data)
117 |
118 | """
119 | Run Bot, To the Moon
120 | """
121 | schedule.every(randint(a,b)).seconds.do(run_bot)
122 | while True:
123 | schedule.run_pending()
124 | time.sleep(0)
--------------------------------------------------------------------------------
/Binance Trading Bot/requirements.txt:
--------------------------------------------------------------------------------
1 | ccxt
2 | parquet
3 | rich
--------------------------------------------------------------------------------
/Binance Trading Bot/supertrend_atr_multiplier_test.py:
--------------------------------------------------------------------------------
1 | #Importation
2 | import ccxt,schedule,warnings,time,ast
3 | warnings.filterwarnings('ignore')
4 | import matplotlib.pyplot as plt
5 | from dateutil.tz import tzlocal
6 | from datetime import datetime
7 | import seaborn as sns
8 | from PIL import Image
9 | import pandas as pd
10 | import numpy as np
11 |
12 | #Set user variables
13 | tick=input("Insert ticker: ")
14 | ticker=tick+"/"+input("USD or USDT?")
15 | timeframe=input("Insert desired time intervals: ")
16 | period=int(input("Period window: "))
17 | volatility=float(input("Volatility rate: "))
18 | limit_frame=int(input("Input 50-50000: "))
19 |
20 | df=exchange.fetch_ohlcv(f'{ticker}', timeframe=timeframe, limit=limit)
21 | df = pd.DataFrame(df[:-1], columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
22 | df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms').dt.tz_localize(None)
23 |
24 | #Supertrend
25 | def tr(data):
26 | data['previous_close']=data['close'].shift(1)
27 | data['high-low']=abs(data['high']-data['low'])
28 | data['high-pc']=abs(data['high']-data['previous_close'])
29 | data['low-pc']=abs(data['low']-data['previous_close'])
30 | tr=data[['high-low','high-pc','low-pc']].max(axis=1)
31 | return tr
32 | def atr(data, period):
33 | data['tr']=tr(data)
34 | atr=data['tr'].rolling(period).mean()
35 | return atr
36 | def supertrend(df,period=period,atr_multiplier=volatility):
37 | hl2=(df['high']+df['low'])/2
38 | df['atr']=atr(df, period)
39 | df['upperband']=hl2+(atr_multiplier*df['atr'])
40 | df['lowerband']=hl2-(atr_multiplier*df['atr'])
41 | df['in_uptrend']=True
42 | for current in range(1,len(df.index)):
43 | previous=current-1
44 | if df['close'][current]>df['upperband'][previous]:
45 | df['in_uptrend'][current]=True
46 | elif df['close'][current]df['upperband'][previous]:
53 | df['upperband'][current]=df['upperband'][previous]
54 | return df
55 |
56 | #Apply supertrend formula
57 | supertrend_data= supertrend(df)
58 |
59 | #Set plot() params
60 | fig, ax = plt.subplots(figsize=(20, 8))
61 |
62 | #Signals 1.1
63 | xcoords_sell = supertrend_data[supertrend_data.in_uptrend == False].index
64 | xcoords_buy = supertrend_data[supertrend_data.in_uptrend == True].index
65 |
66 | #Signals 1.2
67 | for xc in xcoords_sell:
68 | plt.axvline(x=xc,c='r')
69 | for xc in xcoords_buy:
70 | plt.axvline(x=xc,c='g')
71 |
72 | #Plot close price
73 | ax.plot(supertrend_data.close, color = 'black', label = 'Line 1')
74 |
75 | #Plot bollinger bands
76 | ax.plot(supertrend_data.upperband, color = 'lime', label = 'upperband')
77 | ax.plot(supertrend_data.lowerband, color = 'pink', label = 'lowerband')
78 |
79 | #PLot outputs
80 | ax.legend(loc = 'upper left')
81 | plt.savefig(f'supertrend_visual_{tick}_{volatility}.jpg')
82 | plt.show()
83 |
84 | #Open .jpg
85 | Image.open(f"supertrend_visual_{tick}_{volatility}.jpg")
--------------------------------------------------------------------------------
/Cofee Trading™ - DASCIENT:
--------------------------------------------------------------------------------
1 | {"metadata":{"kernelspec":{"display_name":"Python 3","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.8.10"}},"nbformat_minor":4,"nbformat":4,"cells":[{"source":" ","metadata":{},"cell_type":"markdown"},{"cell_type":"markdown","source":"# Simplified Binance Trading & Financial Management\n\nThis workbook serves as the ultimate guide for automating Binance.US trades, recording financial transactions, and planning investment strategies efficiently.\n\n---\n\n## 1. Setup & Installation\n\nInstall the required libraries:\n","metadata":{}},{"cell_type":"code","source":"!pip install pandas numpy requests python-binance pandas-ta python-dotenv","metadata":{},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"---\n\n## 2. Secure API Key Management\n\nStore your Binance API credentials securely using environment variables:\n\n```python\nimport os\nfrom dotenv import load_dotenv\n\nload_dotenv()\napi_key = os.getenv('BINANCE_API_KEY')\napi_secret = os.getenv('BINANCE_API_SECRET')\n```\n\nEnsure your `.env` file contains:\n```plaintext\nBINANCE_API_KEY=your_api_key_here\nBINANCE_API_SECRET=your_secret_key_here\n```\n","metadata":{}},{"cell_type":"markdown","source":"---\n\n## 3. Market Data Retrieval\n\nFetch real-time cryptocurrency market data using the Binance API:\n\n```python\nfrom binance.client import Client\n\nclient = Client(api_key, api_secret)\nbtc_price = client.get_symbol_ticker(symbol='BTCUSDT')\nprint(f'Bitcoin Price: {btc_price['price']}')\n```\n","metadata":{}},{"cell_type":"markdown","source":"---\n\n## 4. Technical Analysis Using pandas_ta\n\nLeverage `pandas_ta` to analyze market trends:\n\n```python\nimport pandas_ta as ta\nimport pandas as pd\n\n# Sample price data\ndf = pd.DataFrame(client.get_historical_klines('BTCUSDT', Client.KLINE_INTERVAL_1HOUR, '1 day ago UTC'))\ndf.columns = ['Time', 'Open', 'High', 'Low', 'Close', 'Volume', 'CloseTime', 'QuoteAssetVolume', 'NumTrades', 'TBBAV', 'TBQAV', 'Ignore']\ndf['Close'] = df['Close'].astype(float)\n\n# Calculate RSI\ndf.ta.rsi(close='Close', length=14, append=True)\nprint(df.tail())\n```\n","metadata":{}}]}
--------------------------------------------------------------------------------
/Jason - Binance Scratchpad/README.md:
--------------------------------------------------------------------------------
1 | **Instructions**
2 |
3 | 1. Open terminal and run: $ python log.py
4 | 2. Open new terminal and run: $ python test.py
5 | 3. Outputs are passed to log.py terminal.
6 |
--------------------------------------------------------------------------------
/Jason - Binance Scratchpad/log_server.py:
--------------------------------------------------------------------------------
1 | import pickle
2 | import logging
3 | import logging.handlers
4 | import socketserver
5 | import struct
6 |
7 |
8 | class LogRecordStreamHandler(socketserver.StreamRequestHandler):
9 | """Handler for a streaming logging request.
10 |
11 | This basically logs the record using whatever logging policy is
12 | configured locally.
13 | """
14 |
15 | def handle(self):
16 | """
17 | Handle multiple requests - each expected to be a 4-byte length,
18 | followed by the LogRecord in pickle format. Logs the record
19 | according to whatever policy is configured locally.
20 | """
21 | while True:
22 | chunk = self.connection.recv(4)
23 | if len(chunk) < 4:
24 | break
25 | slen = struct.unpack('>L', chunk)[0]
26 | chunk = self.connection.recv(slen)
27 | while len(chunk) < slen:
28 | chunk = chunk + self.connection.recv(slen - len(chunk))
29 | obj = self.unPickle(chunk)
30 | record = logging.makeLogRecord(obj)
31 | self.handleLogRecord(record)
32 |
33 | def unPickle(self, data):
34 | return pickle.loads(data)
35 |
36 | def handleLogRecord(self, record):
37 | # if a name is specified, we use the named logger rather than the one
38 | # implied by the record.
39 | if self.server.logname is not None:
40 | name = self.server.logname
41 | else:
42 | name = record.name
43 | logger = logging.getLogger(name)
44 | # N.B. EVERY record gets logged. This is because Logger.handle
45 | # is normally called AFTER logger-level filtering. If you want
46 | # to do filtering, do it at the client end to save wasting
47 | # cycles and network bandwidth!
48 | logger.handle(record)
49 |
50 | class LogRecordSocketReceiver(socketserver.ThreadingTCPServer):
51 | """
52 | Simple TCP socket-based logging receiver suitable for testing.
53 | """
54 |
55 | allow_reuse_address = True
56 |
57 | def __init__(self, host='localhost',
58 | port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
59 | handler=LogRecordStreamHandler):
60 | socketserver.ThreadingTCPServer.__init__(self, (host, port), handler)
61 | self.abort = 0
62 | self.timeout = 1
63 | self.logname = None
64 |
65 | def serve_until_stopped(self):
66 | import select
67 | abort = 0
68 | while not abort:
69 | rd, wr, ex = select.select([self.socket.fileno()],
70 | [], [],
71 | self.timeout)
72 | if rd:
73 | self.handle_request()
74 | abort = self.abort
75 |
76 | def main():
77 | logging.basicConfig(
78 | format='%(asctime)s %(name)-15s %(levelname)-8s %(message)s',
79 | datefmt='%Y-%m-%d %H:%M:%S')
80 | tcpserver = LogRecordSocketReceiver()
81 | print('About to start TCP server...')
82 | tcpserver.serve_until_stopped()
83 |
84 | if __name__ == '__main__':
85 | main()
--------------------------------------------------------------------------------
/Jason - Binance Scratchpad/message.py:
--------------------------------------------------------------------------------
1 | import json
2 | from copy import copy
3 |
4 | __all__ = ['MessageData', 'SELL_MSG', 'BUY_MSG', 'ORDER_MSG']
5 |
6 | class MessageData(object):
7 |
8 | def __init__(self, template, name='MessageData'):
9 | self._template = template
10 | self._name = name
11 | for k, v in self._template.items():
12 | if isinstance(v, dict):
13 | v = MessageData(v, name='.'.join([self._name, k]))
14 | self.__dict__[k] = v
15 |
16 | def __repr__(self):
17 | return f'{self._name}'
18 |
19 | def to_json(self):
20 | keys = [k for k in self.__dict__.keys() if not k.startswith('_')]
21 | data = {k: self.__dict__.get(k) for k in keys}
22 | nested = {k: v for k, v in data.items() if not isinstance(v, str)}
23 | if nested:
24 | body = nested.get('body', '')
25 | if body:
26 | keys = [k for k in body.__dict__.keys() if not k.startswith('_')]
27 | contents = {k: body.__dict__.get(k) for k in keys}
28 | else:
29 | contents = copy(body)
30 | data['body'] = contents
31 | return json.dumps(data)
32 |
33 | ORDER_MSG = {'name': '',
34 | 'type': 'ORDER',
35 | 'body': {'action': '',
36 | 'symbol': '',
37 | 'amount': None,
38 | 'indicator': ''}
39 | }
40 |
41 | SELL_MSG = {'name': '',
42 | 'type': 'ORDER',
43 | 'body': {'action': 'SELL',
44 | 'symbol': '',
45 | 'amount': None,
46 | 'indicator': ''}
47 | }
48 | BUY_MSG = {'name': '',
49 | 'type': 'ORDER',
50 | 'body': {'action': 'BUY',
51 | 'symbol': '',
52 | 'amount': None,
53 | 'indicator': ''}
54 | }
55 |
56 | if __name__ == '__main__':
57 | template = {'name': '', 'type': '', 'body': {'action': '', 'symbol': '', 'amount': None}}
58 | message = MessageData(template)
59 | message.name = 'master'
60 | message.type = 'order'
61 | message.body.action = 'BUY'
62 | message.body.symbol = 'GOOG'
63 | message.body.amount = 100
64 | print(message.to_json())
--------------------------------------------------------------------------------
/Jason - Binance Scratchpad/test.py:
--------------------------------------------------------------------------------
1 | import config
2 | import ccxt
3 | import multiprocessing
4 | from multiprocessing import Process, Pipe, Manager
5 | import threading
6 | import logging
7 | import logging.handlers
8 | import json
9 | from copy import copy, deepcopy
10 | import numpy as np
11 | import schedule
12 | from message import *
13 | import os
14 | import time
15 |
16 |
17 | rootLogger = logging.getLogger('')
18 | rootLogger.setLevel(logging.INFO)
19 | socketHandler = logging.handlers.SocketHandler('localhost', logging.handlers.DEFAULT_TCP_LOGGING_PORT)
20 | rootLogger.addHandler(socketHandler)
21 |
22 |
23 | def wait_until_complete(manager):
24 | processes = multiprocessing.active_children()
25 | while processes:
26 | if len(processes) == 1 and processes[0].name.startswith('SyncManager'):
27 | manager.shutdown()
28 | processes = multiprocessing.active_children()
29 |
30 |
31 | class BinanceMaster(ccxt.binanceus):
32 |
33 | RSI_PERIOD = 14
34 | RSI_OVERBOUGHT = 60
35 | RSI_OVERSOLD = 40
36 | TEST_SYMBOL = 'BTC/USDT'
37 |
38 | def __init__(self, account_config=None, master_id=0, duration=300, interval=30):
39 |
40 | self.master_id = master_id
41 | self.connections = dict()
42 | self.ohlcv_limit = 25
43 | self._kill_run = False
44 | self.duration = duration
45 | self.interval = interval
46 |
47 | if account_config is None or not self._validate_config(account_config):
48 | self.config = {}
49 | else:
50 | self.config = account_config
51 |
52 | def _validate_config(self, config_dict):
53 | try:
54 | contains_api_key = 'apiKey' in config_dict.keys()
55 | contains_secret_key = 'secret' in config_dict.keys()
56 | except Exception:
57 | return False
58 | else:
59 | return contains_api_key and contains_secret_key
60 |
61 | def send_message(self, message, close=False):
62 | for name, conn in self.connections.items():
63 | conn.send(message)
64 | if close:
65 | conn.close()
66 |
67 | def _fetch_close_prices(self):
68 | # using bitcoin ticker for testing
69 | data = self.fetch_ohlcv(self.TEST_SYMBOL, timeframe="1m", limit=self.ohlcv_limit)
70 | # grab 2nd to last element of every OHLCV list for close prices
71 | return np.array([record[-2] for record in data][-(self.RSI_PERIOD+1):])
72 |
73 | def calculate_rsi(self, closes):
74 | # https://www.fidelity.com/learning-center/trading-investing/technical-analysis/technical-indicator-guide/rsi
75 | close_deltas = np.diff(closes)
76 | avg_upward_delta = abs(np.mean(close_deltas[close_deltas >= 0]))
77 | avg_downward_delta = abs(np.mean(close_deltas[close_deltas < 0]))
78 | rsi = 100 - ( 100 / ( 1 + (avg_upward_delta / avg_downward_delta) ) )
79 | return rsi
80 |
81 | def _execute_loop(self, status_table=None):
82 | logger = logging.getLogger(f'maestro-{self.master_id}')
83 | close_prices = self._fetch_close_prices()
84 | rsi = self.calculate_rsi(close_prices)
85 | logger.info(f"RSI VALUE: {str(rsi)}")
86 |
87 | message = MessageData(ORDER_MSG)
88 | message.name = f'maestro-{self.master_id}'
89 | message.body.symbol = self.TEST_SYMBOL
90 | message.body.indicator = 'RSI'
91 |
92 | if rsi > self.RSI_OVERBOUGHT:
93 | message.body.action = 'SELL'
94 | self.send_message(message.to_json())
95 | elif rsi < self.RSI_OVERSOLD:
96 | message.body.action = 'BUY'
97 | self.send_message(message.to_json())
98 | else:
99 | logger.info('RSI ACTION: NONE')
100 |
101 | self.log_status_table(status_table)
102 |
103 | def run(self, connections, status_table):
104 | super().__init__(self.config)
105 | self.connections = connections
106 | self._pid = os.getpid()
107 | status_table[self._pid] = 'up'
108 |
109 | timer = threading.Thread(target=self._timer_thread, daemon=False)
110 | timer.start()
111 |
112 | schedule.every(self.interval).seconds.do(self._execute_loop, status_table=status_table).tag('rsi')
113 |
114 | while True:
115 | schedule.run_pending()
116 | if self._kill_run:
117 | self.send_message('END TRADING', close=True)
118 | schedule.clear('rsi')
119 | break
120 |
121 | status_table[self._pid] = 'down'
122 | self.log_status_table(status_table)
123 |
124 | def _timer_thread(self):
125 | time.sleep(self.duration)
126 | self._kill_run = True
127 |
128 | def log_status_table(self, status_table):
129 | logger = logging.getLogger(f'maestro-{self.master_id}-stat')
130 | try:
131 | d = dict(status_table)
132 | except Exception as e:
133 | logger.info(str(e))
134 | else:
135 | logger.info(json.dumps(d))
136 |
137 |
138 | class BinanceTrader(ccxt.binanceus):
139 |
140 | def __init__(self, name, user_config=None):
141 |
142 | self.user_name = name
143 |
144 | if user_config is None or not self._validate_config(user_config):
145 | self.config = {}
146 | else:
147 | self.config = user_config
148 |
149 | def _validate_config(self, config_dict):
150 | try:
151 | contains_api_key = 'apiKey' in config_dict.keys()
152 | contains_secret_key = 'secret' in config_dict.keys()
153 | except Exception:
154 | return False
155 | else:
156 | return contains_api_key and contains_secret_key
157 |
158 | def get_user_name(self):
159 | return self.user_name
160 |
161 | def recv_message(self, conn):
162 | logger = logging.getLogger(f'{self.get_user_name()}')
163 | while True:
164 | message = conn.recv()
165 | logger.info(message)
166 | if message == 'END TRADING':
167 | conn.close()
168 | break
169 |
170 | def run(self, conn, status_table):
171 | super().__init__(self.config)
172 | self._pid = os.getpid()
173 | status_table[self._pid] = 'up'
174 | self.recv_message(conn)
175 | status_table[self._pid] = 'down'
176 | self.log_status_table(status_table)
177 |
178 | def log_status_table(self, status_table):
179 | logger = logging.getLogger(f'{self.get_user_name()}-stat')
180 | try:
181 | d = dict(status_table)
182 | except Exception as e:
183 | logger.info(str(e))
184 | else:
185 | logger.info(json.dumps(d))
186 |
187 |
188 | if __name__ == '__main__':
189 |
190 | logging.info('starting log')
191 | group = ['trader1', 'trader2']
192 | master_connections = dict()
193 | traders = []
194 |
195 | manager = Manager()
196 | status_table = manager.dict()
197 |
198 | for name in group:
199 | parent_conn, child_conn = Pipe(duplex=True)
200 | master_connections[name] = parent_conn
201 | trader = BinanceTrader(name)
202 | p = Process(target=trader.run, args=(child_conn, status_table), daemon=False)
203 | traders.append(p)
204 |
205 | master_config = {'apiKey': config.API_KEY,
206 | 'secret': config.SECRET_KEY,
207 | 'enableRateLimit': True,
208 | 'options' : {'adjustForTimeDifference': True}}
209 |
210 | master = BinanceMaster(account_config=master_config)
211 | p = Process(target=master.run, args=(master_connections, status_table), daemon=False)
212 | p.start()
213 |
214 | for trader in traders:
215 | trader.start()
216 |
217 | wait_until_complete(manager)
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) ∞ DaScient Capital (A DaScient, LLC subsidiary.)
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/La Vie Bohem - Part 3:
--------------------------------------------------------------------------------
1 | {"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[],"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"source":" ","metadata":{},"cell_type":"markdown"},{"cell_type":"markdown","source":"# **Part 3: Secrets of the Craft – The Second Degree of Mastery** 🔮\n\nWelcome, seeker of knowledge. You are now entering the second degree of mastery in the art of data science and analytics. This is where the craft becomes profound, where you blend skill, creativity, and wisdom to unlock the hidden mysteries of the universe. Let us proceed with discretion and purpose. 🤫","metadata":{}},{"cell_type":"markdown","source":"## **1. The Pillars of Mastery** 🏛️\n\nEvery master stands on the foundation of these three pillars:\n\n- **Knowledge**: A deep understanding of tools, methods, and algorithms.\n- **Wisdom**: Knowing when and how to apply knowledge.\n- **Virtue**: Using skills ethically to benefit humanity.\n\nTake a moment to reflect on how you embody these principles in your work.","metadata":{}},{"cell_type":"markdown","source":"## **2. The Hidden Patterns** 🔢\n\nSeek the unseen by uncovering hidden patterns in data. Here is a secret technique to reveal correlations and anomalies:\n\n- **Correlation Matrices**: Discover relationships between variables.\n- **Anomaly Detection**: Identify outliers that may indicate rare events.\n\nExample: Generating a correlation matrix and visualizing it.","metadata":{}},{"cell_type":"code","source":"import pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\n# Load sample data\nurl = 'https://raw.githubusercontent.com/mwaskom/seaborn-data/master/tips.csv'\ndata = pd.read_csv(url)\n\n# Calculate the correlation matrix\ncorr = data.corr()\n\n# Visualize the correlation matrix\nsns.heatmap(corr, annot=True, cmap='coolwarm', fmt='.2f')\nplt.title('Correlation Matrix')\nplt.show()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## **3. The Symbols of Complexity** ⚙️\n\nIn the complexity of the craft lies its beauty. Master these symbols:\n\n- **Fractals**: Represent infinite complexity within finite bounds.\n- **Chaos Theory**: Understand how small changes create significant impacts.\n\nExample: Visualizing the Mandelbrot set, a fractal of infinite detail.","metadata":{}},{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\n\n# Mandelbrot Set\nx, y = np.linspace(-2.0, 1.0, 1000), np.linspace(-1.5, 1.5, 1000)\nx, y = np.meshgrid(x, y)\nc = x + 1j * y\nz = c\nmandelbrot = np.zeros(c.shape, dtype=int)\n\nfor i in range(100):\n z = z**2 + c\n mask = (mandelbrot == 0) & (abs(z) > 2)\n mandelbrot[mask] = i\n\nplt.imshow(mandelbrot, cmap='inferno', extent=(-2, 1, -1.5, 1.5))\nplt.colorbar(label='Iteration Count')\nplt.title('Mandelbrot Set')\nplt.xlabel('Real Part')\nplt.ylabel('Imaginary Part')\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-16T01:59:39.220008Z","iopub.status.idle":"2025-01-16T01:59:39.220359Z","shell.execute_reply":"2025-01-16T01:59:39.220197Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## **4. The Code of Ethics** 📜\n\nA true master upholds these ethical codes:\n\n1. **Transparency**: Make your methods clear and replicable.\n2. **Equity**: Ensure fairness and eliminate biases in algorithms.\n3. **Accountability**: Accept responsibility for the outcomes of your work.\n\nReflect on these codes as you advance in the craft.","metadata":{}},{"cell_type":"markdown","source":"## **5. Hidden Messages** 🔏\n\nMasters often leave hidden messages for those who follow in their footsteps. Use comments, annotations, and subtle patterns to inspire and guide others.\n\nExample: Embedding a hidden message in your code.","metadata":{}},{"cell_type":"code","source":"# Hidden message example\n\n# This function calculates the Fibonacci sequence.\ndef fibonacci(n):\n \"\"\"\n Fibonacci: A series of numbers where each number is the sum of the two preceding ones.\n Hidden Wisdom: Great things often have simple origins.\n \"\"\"\n a, b = 0, 1\n for _ in range(n):\n yield a\n a, b = b, a + b\n\n# Generate the first 10 Fibonacci numbers\nlist(fibonacci(10))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-16T01:59:39.221484Z","iopub.status.idle":"2025-01-16T01:59:39.221954Z","shell.execute_reply":"2025-01-16T01:59:39.22174Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## **Conclusion** 🏁\n\nYou have taken another step in mastering the craft. Remember to:\n\n- Seek knowledge with humility.\n- Share wisdom with generosity.\n- Build solutions with virtue.\n\nMay your path be illuminated by curiosity and creativity. 🔮","metadata":{}}]}
--------------------------------------------------------------------------------
/La Vie Bohem - Whispers of the Infinite:
--------------------------------------------------------------------------------
1 | {"metadata":{"kernelspec":{"display_name":"Python 3","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.9"},"kaggle":{"accelerator":"none","dataSources":[],"dockerImageVersionId":30839,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"source":" ","metadata":{},"cell_type":"markdown"},{"cell_type":"markdown","source":"# **Unlock ChatGPT's Infinite Potential: EXPOSED!** 🌌\n### You're on your own... get this one to run. Good luck, [@jay.powersurge](https://www.instagram.com/jay.powersurge/)\nWelcome to the ultimate guide on ChatGPT's capabilities! This notebook will showcase the breadth and depth of what ChatGPT can help you achieve, from coding marvels to creative explorations. Prepare to be inspired, and remember: knowledge shared is knowledge multiplied. 🤝\n\n# **Part 4: Free Your Mind – Embrace the Matrix** 🔌\n\nWelcome, seeker. To truly master the craft, you must go beyond the physical and connect with the universal matrix of information. This is not about abandoning reality but understanding its code and transcending its boundaries. 🧠💾\n\n## Series Links\n\n1. [**La Vie Bohem - Coding Republic (Introduction)**](https://www.kaggle.com/code/dascient/la-vie-bohem-coding-republic) \n2. [**La Vie Bohem - Part 2: Data Exploration and Visualization**](https://www.kaggle.com/code/dascient/la-vie-bohem-part-2) \n3. [**La Vie Bohem - Part 3: Advanced Modeling Techniques**](https://www.kaggle.com/code/dascient/la-vie-bohem-part-3) \n4. [**La Vie Bohem - Part 4: Model Evaluation and Tuning**](https://www.kaggle.com/code/dascient/la-vie-bohem-part-4)\n4. [**La Vie Bohem - Part 4a: Extra Credit**](https://www.kaggle.com/code/dascient/la-vie-bohem-part-4a)\n5. [**La Vie Bohem - Whispers of the Infinite**](https://www.kaggle.com/code/dascient/la-vie-bohem-whispers-of-the-infinite) \n\n---\n\n### 🌌 Whispers of Creativity and Infinite Potential 🌌","metadata":{}},{"cell_type":"markdown","source":"## **1. Conversational Mastery** 🧠\n\nChatGPT can:\n\n- Help you brainstorm ideas.\n- Simplify complex concepts.\n- Offer insights into diverse topics.\n\n**Example**: Let's summarize a research abstract.","metadata":{}},{"cell_type":"code","source":"# Example: Summarizing a research abstract\n\ndef summarize(text, max_length=100):\n \"\"\"Summarize a given text.\"\"\"\n return \"Key points from the text: Simplified and concise.\" # Placeholder function\n\n# Input abstract\nabstract = \"Artificial Intelligence is revolutionizing industries with applications spanning healthcare, finance, education, and beyond.\"\nprint(\"Summary:\", summarize(abstract))","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## **2. Data Science and Machine Learning Expertise** 📊\n\nChatGPT excels at:\n\n- Crafting efficient machine learning pipelines.\n- Debugging and optimizing your code.\n- Explaining complex algorithms.\n\n**Example**: Building a predictive model using `scikit-learn`.","metadata":{}},{"cell_type":"code","source":"from sklearn.ensemble import RandomForestClassifier\nfrom sklearn.datasets import load_iris\nfrom sklearn.model_selection import train_test_split\n\n# Load dataset\nX, y = load_iris(return_X_y=True)\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n\n# Train a Random Forest model\nmodel = RandomForestClassifier(random_state=42)\nmodel.fit(X_train, y_train)\n\n# Evaluate the model\naccuracy = model.score(X_test, y_test)\nprint(f\"Model Accuracy: {accuracy:.2f}\")","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## **3. Creative Coding and Visualization** 🎨\n\nLet's create something visually stunning—a cascading matrix effect!","metadata":{}},{"cell_type":"code","source":"from IPython.core.display import display, HTML\n\n# HTML for cascading matrix effect\nhtml_code = '''\n\n\n\n \n'''\n\n# Display the HTML\ndisplay(HTML(html_code))","metadata":{"trusted":true,"html":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## **4. Leverage Open-Source Resources** 🌍\n\nDiscover the best tools and datasets:\n\n- **[DASCIENT, LLC](https://dascient.com)**: Cutting-edge analytics services.\n- **[@donutz.ai](https://donutz.ai)**: A hub for AI creativity and collaboration.\n- **[Kaggle](https://kaggle.com)**: Explore datasets, competitions, and code.\n\nHarness these resources to supercharge your projects!","metadata":{}},{"cell_type":"markdown","source":"## **5. Conclusion** 🏁\n\nWith ChatGPT by your side, the possibilities are endless. Embrace curiosity, creativity, and humility as you explore the infinite world of knowledge and potential. Let your journey begin! 🌟","metadata":{}}]}
--------------------------------------------------------------------------------
/Parquet/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DaScient/SuperTrendTradingBot/f8070baa52422d1d5c39b646047a305db295b873/Parquet/.DS_Store
--------------------------------------------------------------------------------
/Parquet/.ipynb_checkpoints/supertrend_visual_BTC-USDT-checkpoint.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DaScient/SuperTrendTradingBot/f8070baa52422d1d5c39b646047a305db295b873/Parquet/.ipynb_checkpoints/supertrend_visual_BTC-USDT-checkpoint.jpg
--------------------------------------------------------------------------------
/Parquet/.ipynb_checkpoints/supertrend_visual_ETH-USDT-checkpoint.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DaScient/SuperTrendTradingBot/f8070baa52422d1d5c39b646047a305db295b873/Parquet/.ipynb_checkpoints/supertrend_visual_ETH-USDT-checkpoint.jpg
--------------------------------------------------------------------------------
/Parquet/.ipynb_checkpoints/supertrend_visual_LTC-USDT-checkpoint.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DaScient/SuperTrendTradingBot/f8070baa52422d1d5c39b646047a305db295b873/Parquet/.ipynb_checkpoints/supertrend_visual_LTC-USDT-checkpoint.jpg
--------------------------------------------------------------------------------
/Parquet/.ipynb_checkpoints/supertrend_visualizer-checkpoint.py:
--------------------------------------------------------------------------------
1 | #Welcome to the SuperTrend Trading Bot Visualizer!
2 | #Here we can backtest the supertrend forumal over historical timeframes provcided by Binance's Kaggle database.
3 | #https://www.kaggle.com/jorijnsmit/binance-full-history
4 |
5 | from IPython.display import clear_output
6 |
7 | #If this is the first run of binance_bot, please uncomment the !pip install command below
8 | #!pip install -r "requirements.txt"
9 |
10 | import ccxt,schedule,warnings,time,ast
11 | warnings.filterwarnings('ignore')
12 | import matplotlib.pyplot as plt
13 | from dateutil.tz import tzlocal
14 | from datetime import datetime
15 | import pyarrow.parquet as pq
16 | import seaborn as sns
17 |
18 | from PIL import Image
19 | import pandas as pd
20 | import numpy as np
21 |
22 | #Supertrend Formula
23 | def tr(data):
24 | data['previous_close'] = data['close'].shift(1)
25 | data['high-low'] = abs(data['high'] - data['low'])
26 | data['high-pc'] = abs(data['high'] - data['previous_close'])
27 | data['low-pc'] = abs(data['low'] - data['previous_close'])
28 | tr = data[['high-low', 'high-pc', 'low-pc']].max(axis=1)
29 | return tr
30 | def atr(data, period):
31 | data['tr'] = tr(data)
32 | atr = data['tr'].rolling(period).mean()
33 | return atr
34 | def supertrend(df, period=7, atr_multiplier=3):
35 | hl2 = (df['high'] + df['low']) / 2
36 | df['atr'] = atr(df, period)
37 | df['upperband'] = hl2 + (atr_multiplier * df['atr'])
38 | df['lowerband'] = hl2 - (atr_multiplier * df['atr'])
39 | df['in_uptrend'] = True
40 | for current in range(1, len(df.index)):
41 | previous = current - 1
42 | if df['close'][current] > df['upperband'][previous]:
43 | df['in_uptrend'][current] = True
44 | elif df['close'][current] < df['lowerband'][previous]:
45 | df['in_uptrend'][current] = False
46 | else:
47 | df['in_uptrend'][current] = df['in_uptrend'][previous]
48 | if df['in_uptrend'][current] and df['lowerband'][current] < df['lowerband'][previous]:
49 | df['lowerband'][current] = df['lowerband'][previous]
50 | if not df['in_uptrend'][current] and df['upperband'][current] > df['upperband'][previous]:
51 | df['upperband'][current] = df['upperband'][previous]
52 | return df
53 |
54 | #Set user variables
55 | ticker=input("Insert the prefix of your ticker of choice: (example: LTC-USDT) ")
56 |
57 | #Read in historical data.
58 | df = pq.read_table(f'{ticker}.parquet').to_pandas().reset_index(drop=False)
59 | df = df.set_index('open_time')['close'].resample('1m').ohlc().reset_index(drop=False)
60 |
61 | #Apply supertrend formula
62 | supertrend_data= supertrend(df)
63 |
64 | #Set plot() params
65 | fig, ax = plt.subplots(figsize=(20, 8))
66 |
67 | #Signals 1.1
68 | xcoords_sell = supertrend_data.head(500)[supertrend_data.in_uptrend == False].index
69 | xcoords_buy = supertrend_data.head(500)[supertrend_data.in_uptrend == True].index
70 |
71 | #Signals 1.2
72 | for xc in xcoords_sell:
73 | plt.axvline(x=xc,c='r')
74 | for xc in xcoords_buy:
75 | plt.axvline(x=xc,c='g')
76 |
77 | #Plot close price
78 | ax.plot(supertrend_data.head(500).close, color = 'black', label = 'Line 1')
79 |
80 | #Plot bollinger bands
81 | #ax.plot(supertrend_data.tail(5000).upperband, color = 'lime', label = 'upperband')
82 | #ax.plot(supertrend_data.tail(5000).lowerband, color = 'pink', label = 'lowerband')
83 |
84 | #PLot outputs
85 | ax.legend(loc = 'upper left')
86 | plt.savefig(f'supertrend_visual_{ticker}.jpg')
87 | plt.show()
88 |
89 | #Open .jpg
90 | Image.open("supertrend_visual_{ticker}.jpg")
--------------------------------------------------------------------------------
/Parquet/DOGE-USDT.parquet:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DaScient/SuperTrendTradingBot/f8070baa52422d1d5c39b646047a305db295b873/Parquet/DOGE-USDT.parquet
--------------------------------------------------------------------------------
/Parquet/README.md:
--------------------------------------------------------------------------------
1 | # CryptoBot - SuperTrend Algorithm
2 |
3 | ---
4 |
5 | ## Backtest :robot:
6 |
7 | Here's a snapshot of supertrend's performance on ETHEREUM in a two month historical time period.
8 |
9 | 
--------------------------------------------------------------------------------
/Parquet/requirements.txt:
--------------------------------------------------------------------------------
1 | ccxt
2 | parquet
--------------------------------------------------------------------------------
/Parquet/supertrend_visual_BTC-USDT.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DaScient/SuperTrendTradingBot/f8070baa52422d1d5c39b646047a305db295b873/Parquet/supertrend_visual_BTC-USDT.jpg
--------------------------------------------------------------------------------
/Parquet/supertrend_visual_ETH-USDT.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DaScient/SuperTrendTradingBot/f8070baa52422d1d5c39b646047a305db295b873/Parquet/supertrend_visual_ETH-USDT.jpg
--------------------------------------------------------------------------------
/Parquet/supertrend_visual_LTC-USDT.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DaScient/SuperTrendTradingBot/f8070baa52422d1d5c39b646047a305db295b873/Parquet/supertrend_visual_LTC-USDT.jpg
--------------------------------------------------------------------------------
/Parquet/supertrend_visualizer.py:
--------------------------------------------------------------------------------
1 | #Welcome to the SuperTrend Trading Bot Visualizer!
2 | #Here we can backtest the supertrend forumal over historical timeframes provcided by Binance's Kaggle database.
3 | #https://www.kaggle.com/jorijnsmit/binance-full-history
4 |
5 | from IPython.display import clear_output
6 |
7 | #If this is the first run of binance_bot, please uncomment the !pip install command below
8 | #!pip install -r "requirements.txt"
9 |
10 | import ccxt,schedule,warnings,time,ast
11 | warnings.filterwarnings('ignore')
12 | import matplotlib.pyplot as plt
13 | from dateutil.tz import tzlocal
14 | from datetime import datetime
15 | import pyarrow.parquet as pq
16 | import seaborn as sns
17 |
18 | from PIL import Image
19 | import pandas as pd
20 | import numpy as np
21 |
22 | #Supertrend Formula
23 | def tr(data):
24 | data['previous_close'] = data['close'].shift(1)
25 | data['high-low'] = abs(data['high'] - data['low'])
26 | data['high-pc'] = abs(data['high'] - data['previous_close'])
27 | data['low-pc'] = abs(data['low'] - data['previous_close'])
28 | tr = data[['high-low', 'high-pc', 'low-pc']].max(axis=1)
29 | return tr
30 | def atr(data, period):
31 | data['tr'] = tr(data)
32 | atr = data['tr'].rolling(period).mean()
33 | return atr
34 | def supertrend(df, period=7, atr_multiplier=3):
35 | hl2 = (df['high'] + df['low']) / 2
36 | df['atr'] = atr(df, period)
37 | df['upperband'] = hl2 + (atr_multiplier * df['atr'])
38 | df['lowerband'] = hl2 - (atr_multiplier * df['atr'])
39 | df['in_uptrend'] = True
40 | for current in range(1, len(df.index)):
41 | previous = current - 1
42 | if df['close'][current] > df['upperband'][previous]:
43 | df['in_uptrend'][current] = True
44 | elif df['close'][current] < df['lowerband'][previous]:
45 | df['in_uptrend'][current] = False
46 | else:
47 | df['in_uptrend'][current] = df['in_uptrend'][previous]
48 | if df['in_uptrend'][current] and df['lowerband'][current] < df['lowerband'][previous]:
49 | df['lowerband'][current] = df['lowerband'][previous]
50 | if not df['in_uptrend'][current] and df['upperband'][current] > df['upperband'][previous]:
51 | df['upperband'][current] = df['upperband'][previous]
52 | return df
53 |
54 | #Set user variables
55 | ticker=input("Insert the prefix of your ticker of choice: (example: LTC-USDT) ")
56 |
57 | #Read in historical data.
58 | df = pq.read_table(f'{ticker}.parquet').to_pandas().reset_index(drop=False)
59 | df = df.set_index('open_time')['close'].resample('1m').ohlc().reset_index(drop=False)
60 |
61 | #Apply supertrend formula
62 | supertrend_data= supertrend(df)
63 |
64 | #Set plot() params
65 | fig, ax = plt.subplots(figsize=(20, 8))
66 |
67 | #Signals 1.1
68 | xcoords_sell = supertrend_data.head(500)[supertrend_data.in_uptrend == False].index
69 | xcoords_buy = supertrend_data.head(500)[supertrend_data.in_uptrend == True].index
70 |
71 | #Signals 1.2
72 | for xc in xcoords_sell:
73 | plt.axvline(x=xc,c='r')
74 | for xc in xcoords_buy:
75 | plt.axvline(x=xc,c='g')
76 |
77 | #Plot close price
78 | ax.plot(supertrend_data.head(500).close, color = 'black', label = 'Line 1')
79 |
80 | #Plot bollinger bands
81 | #ax.plot(supertrend_data.tail(5000).upperband, color = 'lime', label = 'upperband')
82 | #ax.plot(supertrend_data.tail(5000).lowerband, color = 'pink', label = 'lowerband')
83 |
84 | #PLot outputs
85 | ax.legend(loc = 'upper left')
86 | plt.savefig(f'supertrend_visual_{ticker}.jpg')
87 | plt.show()
88 |
89 | #Open .jpg
90 | Image.open("supertrend_visual_{ticker}.jpg")
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Super Trend Trading Bot
2 |
3 | Welcome to the [@donutz.ai](https://donutz.ai) automated trading protocol - a [DASCIENT, LLC](https://dascient.com) proprietary bot that leverages cutting-edge **Reinforcement Learning ensembles**, the **SuperTrend indicator**, **Kalman Filter Forecasting**, **Simple & Exponential Moving Averages**, **Relative Strength Index (RSI)**, and other robust technical indicators to generate intelligent trade signals. It calculates and suggests profitable buy/sell orders for both **Robinhood** and **Binance.US** platforms using **Python**.
4 |
5 | This project is an open-source playground for data scientists, quants, and trading enthusiasts alike. **Fork**, **tweak**, **experiment**, and **enhance** to your heart's content! The underlying decision science and forecasting principles here are widely applicable across predictive modeling, time-series analysis, and machine learning efforts well beyond trading and asset management. We only ask you to credit this repository and respect our community's guidelines.
6 |
7 | For detailed insights into the bot's development and functionality, check out this [Medium publication](https://medium.com/coinmonks/daily-binance-us-crypto-trade-signals-fda4e8a205c8) and this [Kaggle Notebook](https://www.kaggle.com/code/dascient/daily-crypto-buy-sell-decision-maker), which showcases automated decision-making in action.
8 |
9 | ---
10 |
11 | ## **Current Development Goals**
12 |
13 | 1. **Incorporate Social Sentiment Analysis**: Bringing the pulse of the market to your trades.
14 | 2. **Add Advanced Indicators**: Expanding our suite of technical tools.
15 | 3. **Pre-Built Trading Strategies**: Allow users to select and deploy strategies tailored to their goals.
16 | 4. **Community Portfolio Mirroring**: Users can create, share, and mirror peer portfolios for collective success.
17 | 5. **Autonomous Hyperparameter Tuning**: Optimizing the bot’s decision-making as it learns and adapts over time.
18 |
19 | We aim to optimize returns, minimize losses, and make trading as straightforward (and enjoyable) as possible. Join us in building a platform for traders of all levels—because making smarter trades shouldn’t be intimidating.
20 |
21 | ---
22 |
23 | ## **SuperTrend Features** :computer:
24 |
25 | ### **Trends**
26 | This unique feature lets users partially or fully mirror portfolio allocations of others in the community. Explore strategies, join public groups, or even create your own portfolios to share. When a group leader updates their allocations, all connected portfolios will automatically reflect the changes! It’s like being part of a live, dynamic investment team—designed for all risk appetites.
27 |
28 | ---
29 |
30 | ## **The Bot: SuperTrend in a Nutshell** :robot:
31 |
32 | The bot is organized into three main components:
33 |
34 | 1. **Data Class**: Handles live market data, including candlestick (OHLC) feeds and key indicators.
35 | 2. **Trade Strategy Class**: A modular system allowing users to experiment with various trading strategies.
36 | 3. **Execution Class**: Converts trade signals into live orders on Binance.US via the CCXT library.
37 |
38 | ---
39 |
40 | ## **What You'll Need**
41 |
42 | Even though we’re working hard to release a fully user-friendly version, you can still test the bot locally. Fork the repo, give it a star, and follow our progress. If you have ideas to improve efficiency, scalability, or features—send them our way!
43 |
44 | ### **Requirements**
45 | 1. **[Python (3.9.7+)](https://www.python.org/ftp/python/3.9.7/python-3.9.7-macosx10.9.pkg)**
46 | 2. **Jupyter Notebook/Anaconda** ([Miniconda works too](https://docs.conda.io/en/latest/miniconda.html))
47 | 3. **Binance.US account** ([Sign up here](https://accounts.binance.us/en/register?ref=52441695))
48 | 4. Clone this repo to your local machine (e.g., `~/Desktop/GitHub`).
49 |
50 | **Setting Up Binance.US API:**
51 | 1. Log in, navigate to **API Management**, and create a new API key.
52 | 2. Safely store your `API_KEY` and `API_SECRET` in a `config.py` file. Use [this format](https://github.com/DaScient/SuperTrendTradingBot/blob/main/Binance%20Trading%20Bot/config.py) for reference.
53 |
54 | ---
55 |
56 | ## **How to Run**
57 |
58 | To execute the bot, navigate to its directory in your terminal and run:
59 | ```bash
60 | $ python binance_bot.py
61 |
62 | # For the Reinforcement Learning Mod, follow these instructions.
63 |
64 | Components Overview
65 |
66 | Data Class
67 |
68 | Connects to Binance.US via CCXT WebSocket for live candlestick (OHLC) data. Includes rolling averages, Bollinger Bands, and binary indicators for trend detection.
69 |
70 | Trade Strategy Class
71 |
72 | A modular framework that supports a variety of trading strategies. Plug in your custom strategy—if it generates buy/sell signals, it’s good to go!
73 |
74 | Execution Class
75 |
76 | Executes buy/sell orders on Binance.US based on trade signals using CCXT integration.
77 |
78 | Resources & Repositories
79 | • Part Time Larry’s SuperTrend Crypto Bot
80 | • Part Time Larry’s Binance Tutorials
81 | • CCXT Binance.US Integration
82 | • Binance Full History Dataset (2017-2020)
83 |
84 | Stay hydrated, have fun, and happy trading! :chart_with_upwards_trend:
--------------------------------------------------------------------------------
/RL-Binance/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DaScient/SuperTrendTradingBot/f8070baa52422d1d5c39b646047a305db295b873/RL-Binance/.DS_Store
--------------------------------------------------------------------------------
/RL-Binance/2022_03_26_09_39_VTHO_Crypto_trader/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DaScient/SuperTrendTradingBot/f8070baa52422d1d5c39b646047a305db295b873/RL-Binance/2022_03_26_09_39_VTHO_Crypto_trader/.DS_Store
--------------------------------------------------------------------------------
/RL-Binance/2022_03_26_09_39_VTHO_Crypto_trader/.ipynb_checkpoints/Parameters-checkpoint.json:
--------------------------------------------------------------------------------
1 | {
2 | "training start": "2022-03-26 09:42",
3 | "initial balance": 1000,
4 | "training episodes": 5000,
5 | "lookback window size": 150,
6 | "depth": 13,
7 | "lr": 1e-05,
8 | "epochs": 5,
9 | "batch size": 32,
10 | "normalize value": 40000,
11 | "model": "CNN",
12 | "comment": "Normalized",
13 | "saving time": "2022-03-26 10:04",
14 | "Actor name": "1231.89_Crypto_trader_Actor.h5",
15 | "Critic name": "1231.89_Crypto_trader_Critic.h5"
16 | }
--------------------------------------------------------------------------------
/RL-Binance/2022_03_26_09_39_VTHO_Crypto_trader/.ipynb_checkpoints/log-checkpoint.txt:
--------------------------------------------------------------------------------
1 | 2022-03-26 09:46:25, 101, 1136.727691506716, 97, -0.05475713113322854, 3066.6462304687498
2 | 2022-03-26 09:47:12, 113, 1140.2573962071297, 93, -0.01287351858491699, 78640.71466145833
3 | 2022-03-26 09:47:51, 128, 1144.0634135966675, 99, -0.024914896624783675, 91516.902734375
4 | 2022-03-26 10:01:23, 459, 1151.2839701438963, 71, -0.031319348116715745, 749376.9122395833
5 | 2022-03-26 10:01:25, 460, 1156.9089552764517, 83, -0.02101700269927581, 56117.982434895835
6 | 2022-03-26 10:01:27, 461, 1160.3870546583996, 69, -0.025871823529402413, 6913.686250813802
7 | 2022-03-26 10:01:29, 462, 1164.6851131177216, 77, -0.007214625974496206, 50416.37154947917
8 | 2022-03-26 10:02:51, 497, 1166.3527433515662, 77, -0.052624337598681445, 7536.4572737630215
9 | 2022-03-26 10:03:04, 501, 1171.3259564128314, 81, -0.044973972340424856, 12310.919698079428
10 | 2022-03-26 10:03:11, 504, 1196.0280898061094, 57, -0.03452135501429439, 1210183.75546875
11 | 2022-03-26 10:03:14, 505, 1199.685704140907, 60, 0.0006017878403266272, 9970.349855957033
12 | 2022-03-26 10:03:16, 506, 1206.5577373590654, 61, 0.014881325860818227, 15167.055105794272
13 | 2022-03-26 10:03:18, 507, 1208.7535824443792, 62, -0.03316492053369681, 6658.00292154948
14 | 2022-03-26 10:04:25, 537, 1217.3450733575303, 73, -0.005562761873006821, 271543.64208333334
15 | 2022-03-26 10:04:27, 538, 1221.0757395293758, 59, -0.0020365287363529206, 22333.67515625
16 | 2022-03-26 10:04:37, 543, 1231.3321265463153, 63, 0.011519612471262614, 355145.6220833333
17 | 2022-03-26 10:04:39, 544, 1231.8936835641307, 56, 0.0024635383486747743, 12131.09403889974
18 |
--------------------------------------------------------------------------------
/RL-Binance/2022_03_26_09_39_VTHO_Crypto_trader/1283.77_Crypto_trader_Actor.h5:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DaScient/SuperTrendTradingBot/f8070baa52422d1d5c39b646047a305db295b873/RL-Binance/2022_03_26_09_39_VTHO_Crypto_trader/1283.77_Crypto_trader_Actor.h5
--------------------------------------------------------------------------------
/RL-Binance/2022_03_26_09_39_VTHO_Crypto_trader/1283.77_Crypto_trader_Critic.h5:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DaScient/SuperTrendTradingBot/f8070baa52422d1d5c39b646047a305db295b873/RL-Binance/2022_03_26_09_39_VTHO_Crypto_trader/1283.77_Crypto_trader_Critic.h5
--------------------------------------------------------------------------------
/RL-Binance/2022_03_26_09_39_VTHO_Crypto_trader/1284.68_Crypto_trader_Actor.h5:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DaScient/SuperTrendTradingBot/f8070baa52422d1d5c39b646047a305db295b873/RL-Binance/2022_03_26_09_39_VTHO_Crypto_trader/1284.68_Crypto_trader_Actor.h5
--------------------------------------------------------------------------------
/RL-Binance/2022_03_26_09_39_VTHO_Crypto_trader/1284.68_Crypto_trader_Critic.h5:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DaScient/SuperTrendTradingBot/f8070baa52422d1d5c39b646047a305db295b873/RL-Binance/2022_03_26_09_39_VTHO_Crypto_trader/1284.68_Crypto_trader_Critic.h5
--------------------------------------------------------------------------------
/RL-Binance/2022_03_26_09_39_VTHO_Crypto_trader/Parameters.json:
--------------------------------------------------------------------------------
1 | {
2 | "training start": "2022-03-26 09:42",
3 | "initial balance": 1000,
4 | "training episodes": 5000,
5 | "lookback window size": 150,
6 | "depth": 13,
7 | "lr": 1e-05,
8 | "epochs": 5,
9 | "batch size": 32,
10 | "normalize value": 40000,
11 | "model": "CNN",
12 | "comment": "Normalized",
13 | "saving time": "2022-03-26 10:16",
14 | "Actor name": "1284.68_Crypto_trader_Actor.h5",
15 | "Critic name": "1284.68_Crypto_trader_Critic.h5"
16 | }
--------------------------------------------------------------------------------
/RL-Binance/2022_03_26_09_39_VTHO_Crypto_trader/log.txt:
--------------------------------------------------------------------------------
1 | 2022-03-26 09:46:25, 101, 1136.727691506716, 97, -0.05475713113322854, 3066.6462304687498
2 | 2022-03-26 09:47:12, 113, 1140.2573962071297, 93, -0.01287351858491699, 78640.71466145833
3 | 2022-03-26 09:47:51, 128, 1144.0634135966675, 99, -0.024914896624783675, 91516.902734375
4 | 2022-03-26 10:01:23, 459, 1151.2839701438963, 71, -0.031319348116715745, 749376.9122395833
5 | 2022-03-26 10:01:25, 460, 1156.9089552764517, 83, -0.02101700269927581, 56117.982434895835
6 | 2022-03-26 10:01:27, 461, 1160.3870546583996, 69, -0.025871823529402413, 6913.686250813802
7 | 2022-03-26 10:01:29, 462, 1164.6851131177216, 77, -0.007214625974496206, 50416.37154947917
8 | 2022-03-26 10:02:51, 497, 1166.3527433515662, 77, -0.052624337598681445, 7536.4572737630215
9 | 2022-03-26 10:03:04, 501, 1171.3259564128314, 81, -0.044973972340424856, 12310.919698079428
10 | 2022-03-26 10:03:11, 504, 1196.0280898061094, 57, -0.03452135501429439, 1210183.75546875
11 | 2022-03-26 10:03:14, 505, 1199.685704140907, 60, 0.0006017878403266272, 9970.349855957033
12 | 2022-03-26 10:03:16, 506, 1206.5577373590654, 61, 0.014881325860818227, 15167.055105794272
13 | 2022-03-26 10:03:18, 507, 1208.7535824443792, 62, -0.03316492053369681, 6658.00292154948
14 | 2022-03-26 10:04:25, 537, 1217.3450733575303, 73, -0.005562761873006821, 271543.64208333334
15 | 2022-03-26 10:04:27, 538, 1221.0757395293758, 59, -0.0020365287363529206, 22333.67515625
16 | 2022-03-26 10:04:37, 543, 1231.3321265463153, 63, 0.011519612471262614, 355145.6220833333
17 | 2022-03-26 10:04:39, 544, 1231.8936835641307, 56, 0.0024635383486747743, 12131.09403889974
18 | 2022-03-26 10:11:24, 733, 1240.173521477777, 39, 0.015136425942182542, 277345.990546875
19 | 2022-03-26 10:11:26, 734, 1240.978203918933, 99, -0.0615332782206436, 9117.44574625651
20 | 2022-03-26 10:11:28, 735, 1265.226267255996, 39, -0.0005085565149784079, 366817.0313541667
21 | 2022-03-26 10:11:44, 742, 1270.588954864226, 106, -0.03584370573361714, 218727.23758789065
22 | 2022-03-26 10:13:23, 793, 1274.0988825361178, 93, -0.06254836224640409, 101311.40740885417
23 | 2022-03-26 10:13:34, 799, 1280.3249923351227, 79, -0.026809503485759098, 162986.1445703125
24 | 2022-03-26 10:13:36, 800, 1283.7659706653253, 109, -0.021281710111846527, 7291.508936360677
25 | 2022-03-26 10:16:20, 877, 1284.6755100895466, 107, -0.040243529255191486, 573936.34765625
26 |
--------------------------------------------------------------------------------
/RL-Binance/DOGE-USDT.parquet:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DaScient/SuperTrendTradingBot/f8070baa52422d1d5c39b646047a305db295b873/RL-Binance/DOGE-USDT.parquet
--------------------------------------------------------------------------------
/RL-Binance/README.md:
--------------------------------------------------------------------------------
1 | **Instructions**
2 |
3 | *To run baseline (non-RL)*
4 | 1. Open terminal and run: $ python log.py
5 | 2. Open new temrinal and run: $ python test.py
6 | 3. Outputs are passed to log.py terminal.
7 |
8 | *To run RL model*
9 | 1. $ python RL-Binance-bot.py
10 | 2. Follow prompt.
11 |
12 | Still needs to be integrated into test.py & binance market_fetch().
13 |
--------------------------------------------------------------------------------
/RL-Binance/VTHO-USDT.parquet:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DaScient/SuperTrendTradingBot/f8070baa52422d1d5c39b646047a305db295b873/RL-Binance/VTHO-USDT.parquet
--------------------------------------------------------------------------------
/RL-Binance/__pycache__/indicators.cpython-38.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DaScient/SuperTrendTradingBot/f8070baa52422d1d5c39b646047a305db295b873/RL-Binance/__pycache__/indicators.cpython-38.pyc
--------------------------------------------------------------------------------
/RL-Binance/__pycache__/model.cpython-38.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DaScient/SuperTrendTradingBot/f8070baa52422d1d5c39b646047a305db295b873/RL-Binance/__pycache__/model.cpython-38.pyc
--------------------------------------------------------------------------------
/RL-Binance/__pycache__/multiprocessing_env.cpython-38.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DaScient/SuperTrendTradingBot/f8070baa52422d1d5c39b646047a305db295b873/RL-Binance/__pycache__/multiprocessing_env.cpython-38.pyc
--------------------------------------------------------------------------------
/RL-Binance/__pycache__/utils.cpython-38.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DaScient/SuperTrendTradingBot/f8070baa52422d1d5c39b646047a305db295b873/RL-Binance/__pycache__/utils.cpython-38.pyc
--------------------------------------------------------------------------------
/RL-Binance/indicators.py:
--------------------------------------------------------------------------------
1 | {"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[],"dockerImageVersionId":30822,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# [Portfolio Management](www.donutz.ai)\n## [Sign up today!](https://donutz.ai/#)","metadata":{}},{"cell_type":"code","source":"from IPython.display import clear_output\n!pip install pandas_ta,schedule,pykalman\nclear_output()\nimport schedule,warnings,smtplib,random\nfrom pykalman import KalmanFilter\nfrom dateutil.tz import tzlocal\nfrom datetime import datetime\nfrom decimal import Decimal\nfrom random import randint\nfrom random import seed\nimport pandas_ta as ta\nimport pandas as pd\nimport numpy as np\nwarnings.filterwarnings('ignore')\nrand = random.randint(1,23)","metadata":{"trusted":true,"_kg_hide-input":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"if rand < 13:\n tick='btc'#input(\"crypto ticker:\")\nelse:\n tick='shib'\nif tick=='btc':\n df = pd.read_csv('https://www.cryptodatadownload.com/cdd/Binance_BTCUSDT_1h.csv',header=1)\n df.Close.tail(200).plot(figsize=(25,7))\nif tick=='shib':\n df = pd.read_csv('https://www.cryptodatadownload.com/cdd/Binance_SHIBUSDT_1h.csv',header=1)\n df.Close.tail(200).plot(figsize=(25,7))\n#if tick=='pepe':\n# df = pd.read_csv('https://www.cryptodatadownload.com/cdd/Binance_PEPEUSDT_1h.csv',header=1)\n# df.Close.tail(200).plot(figsize=(25,7))\nCARRIERS = {\"att\": \"@mms.att.net\",\n \"tmobile\": \"@tmomail.net\",\n \"verizon\": \"@vtext.com\",\n \"sprint\": \"@messaging.sprintpcs.com\"}\nif rand < 13:\n EMAIL = \"existentialkingdom@gmail.com\"\n PASSWORD = \"vwzk voak mcfh huee\"\nelse:\n EMAIL = \"aristocles24@gmail.com\"\n PASSWORD = \"odxx ontt dgbz nabo\"\nprint(f\"served by: {EMAIL[:4]}\")","metadata":{"trusted":true,"_kg_hide-input":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def send_message(phone_number, carrier, message):\n recipient = phone_number + CARRIERS[carrier]\n auth = (EMAIL, PASSWORD)\n server = smtplib.SMTP(\"smtp.gmail.com\", 587)\n server.starttls()\n server.login(auth[0], auth[1])\n server.sendmail(auth[0], recipient, message)\ndef supertrend(df):\n df['close'] = df['Close']\n df['low'] = df['Low']\n df['high'] = df['High']\n df['open'] = df['Open']\n close = df['close'][len(df)-1]\n low = df['low'][len(df)-1]\n kf = KalmanFilter(transition_matrices = [1], # The value for At. It is a random walk so is set to 1.0\n observation_matrices = [1], # The value for Ht.\n initial_state_mean = 0, # Any initial value. It will converge to the true state value.\n initial_state_covariance = 1, # Sigma value for the Qt in Equation (1) the Gaussian distribution\n observation_covariance=1, # Sigma value for the Rt in Equation (2) the Gaussian distribution\n transition_covariance=.01) # A small turbulence in the random walk parameter 1.0\n state_means, _ = kf.filter(df['close'].values)\n df['kf_mean'] = np.array(state_means)\n kalman = df.kf_mean[len(df)-1]\n aboveKalman = low > kalman\n ema_13 = df.ta.ema(13, append=True)[-1:].reset_index(drop=True)[0]\n ema_31 = df.ta.ema(31, append=True)[-1:].reset_index(drop=True)[0]\n ema_crossover = ema_13 > kalman\n bbl_14 = df.ta.bbands(length=14, append=True)[['BBL_14_2.0']].tail(1).values[0][0]\n bbu_14 = df.ta.bbands(length=14, append=True)[['BBU_14_2.0']].tail(1).values[0][0]\n bband_buy = close < bbl_14\n bband_sell = close > bbu_14\n isa_9 = df.ta.ichimoku()[1]['ISA_9'].tail(1).values[0] # help(ta.ichimoku)\n isb_26 = df.ta.ichimoku()[1]['ISB_26'].tail(1).values[0]\n amat = (df.ta.amat()['AMATe_LR_8_21_2'].tail(1).values[0] == 1)\n rsi = df.ta.rsi()[len(df)-1]\n rsi_buy = rsi < 35\n rsi_sell = rsi > 65\n try:chop = \"{:.2f}\".format(df.ta.chop()[len(df.ta.chop())-1]) \n except RunTimeWarning:chop = 0\n buy = ema_13 > kalman\n sell = ema_13 < kalman\n return df, close, isa_9, isb_26, chop, rsi, ema_crossover, buy, sell, aboveKalman\ndef plot(df,symbol):\n fig = go.Figure(go.Candlestick(x=df.index,open=df['open'],high=df['high'],low=df['low'],close=df['close'],name=symbol))\n fig.add_trace(go.Scatter(x=df.index,y=df['kf_mean'],opacity=0.7,line=dict(color='purple', width=2),name='Kalman Filter'))\n fig.add_trace(go.Scatter(x=df.index,y=df['EMA_13'],opacity=0.7,line=dict(color='orange', width=2),name='EMA_13'))\n fig.add_trace(go.Scatter(x=df.index,y=df['EMA_31'],opacity=0.7,line=dict(color='lightblue', width=2),name='EMA_31 '))\n fig.update_layout(title=f'Ticker: {symbol}')\n fig.update_layout(xaxis_rangeslider_visible=False)\n return fig.show()","metadata":{"trusted":true,"_kg_hide-input":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def run_bot():\n print(\"\\ndatetime:\",pd.Timestamp.now())\n techs = supertrend(df)\n if techs[7]:\n print(f\"prev.close:{techs[1]:.10g}\")\n print(f\"Decimal(str({techs[1]}))\")\n print(f\"buy {tick}\")\n print(f\"chop:{techs[4]}\")\n print(f\"rsi:{techs[5]}\")\n send_message(\"3016750611\",\"tmobile\",f\"buy {tick}\")\n if techs[8]:\n print(f\"prev.close:{techs[1]:.10g}\")\n print(f\"Decimal(str({techs[1]}))\")\n print(f\"sell {tick}\")\n print(f\"chop:{techs[4]}\")\n print(f\"rsi:{techs[5]}\")\n send_message(\"3016750611\",\"tmobile\",f\"sell {tick}\")\nschedule.every(3).seconds.do(run_bot)\nwhile True:\n schedule.run_pending()\n time.sleep(0)","metadata":{"trusted":true,"_kg_hide-input":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#en fin","metadata":{"trusted":true,"_kg_hide-input":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Supplement","metadata":{"_kg_hide-input":false}},{"cell_type":"code","source":"chart=df.Close.tail(200).plot(figsize=(25,7))\n\nimport os\nimport smtplib\nfrom email.mime.text import MIMEText\nfrom email.mime.image import MIMEImage\nfrom email.mime.multipart import MIMEMultipart\n\n\ndef SendMail(ImgFileName):\n with open(ImgFileName, 'rb') as f:\n img_data = f.read()\n\n msg = MIMEMultipart()\n msg['Subject'] = 'photo'\n msg['From'] = 'existentialkingdom@gmail.com'\n msg['To'] = '3016750611@tmomail.net'\n\n text = MIMEText(\"test\")\n msg.attach(text)\n image = MIMEImage(chart, name=os.path.basename(ImgFileName))\n msg.attach(image)\n\n s = smtplib.SMTP(Server, Port)\n s.ehlo()\n s.starttls()\n s.ehlo()\n s.login(\"existentialkingdom@gmail.com\", \"vwzk voak mcfh huee\")\n s.sendmail(From, To, msg.as_string())\n s.quit()","metadata":{"trusted":true,"_kg_hide-input":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# enfinissementemundoaliocious","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}
--------------------------------------------------------------------------------
/RL-Binance/log_server.py:
--------------------------------------------------------------------------------
1 | import pickle
2 | import logging
3 | import logging.handlers
4 | import socketserver
5 | import struct
6 |
7 |
8 | class LogRecordStreamHandler(socketserver.StreamRequestHandler):
9 | """Handler for a streaming logging request.
10 |
11 | This basically logs the record using whatever logging policy is
12 | configured locally.
13 | """
14 |
15 | def handle(self):
16 | """
17 | Handle multiple requests - each expected to be a 4-byte length,
18 | followed by the LogRecord in pickle format. Logs the record
19 | according to whatever policy is configured locally.
20 | """
21 | while True:
22 | chunk = self.connection.recv(4)
23 | if len(chunk) < 4:
24 | break
25 | slen = struct.unpack('>L', chunk)[0]
26 | chunk = self.connection.recv(slen)
27 | while len(chunk) < slen:
28 | chunk = chunk + self.connection.recv(slen - len(chunk))
29 | obj = self.unPickle(chunk)
30 | record = logging.makeLogRecord(obj)
31 | self.handleLogRecord(record)
32 |
33 | def unPickle(self, data):
34 | return pickle.loads(data)
35 |
36 | def handleLogRecord(self, record):
37 | # if a name is specified, we use the named logger rather than the one
38 | # implied by the record.
39 | if self.server.logname is not None:
40 | name = self.server.logname
41 | else:
42 | name = record.name
43 | logger = logging.getLogger(name)
44 | # N.B. EVERY record gets logged. This is because Logger.handle
45 | # is normally called AFTER logger-level filtering. If you want
46 | # to do filtering, do it at the client end to save wasting
47 | # cycles and network bandwidth!
48 | logger.handle(record)
49 |
50 | class LogRecordSocketReceiver(socketserver.ThreadingTCPServer):
51 | """
52 | Simple TCP socket-based logging receiver suitable for testing.
53 | """
54 |
55 | allow_reuse_address = True
56 |
57 | def __init__(self, host='localhost',
58 | port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
59 | handler=LogRecordStreamHandler):
60 | socketserver.ThreadingTCPServer.__init__(self, (host, port), handler)
61 | self.abort = 0
62 | self.timeout = 1
63 | self.logname = None
64 |
65 | def serve_until_stopped(self):
66 | import select
67 | abort = 0
68 | while not abort:
69 | rd, wr, ex = select.select([self.socket.fileno()],
70 | [], [],
71 | self.timeout)
72 | if rd:
73 | self.handle_request()
74 | abort = self.abort
75 |
76 | def main():
77 | logging.basicConfig(
78 | format='%(asctime)s %(name)-15s %(levelname)-8s %(message)s',
79 | datefmt='%Y-%m-%d %H:%M:%S')
80 | tcpserver = LogRecordSocketReceiver()
81 | print('About to start TCP server...')
82 | tcpserver.serve_until_stopped()
83 |
84 | if __name__ == '__main__':
85 | main()
--------------------------------------------------------------------------------
/RL-Binance/message.py:
--------------------------------------------------------------------------------
1 | import json
2 | from copy import copy
3 |
4 | __all__ = ['MessageData', 'SELL_MSG', 'BUY_MSG', 'ORDER_MSG']
5 |
6 | class MessageData(object):
7 |
8 | def __init__(self, template, name='MessageData'):
9 | self._template = template
10 | self._name = name
11 | for k, v in self._template.items():
12 | if isinstance(v, dict):
13 | v = MessageData(v, name='.'.join([self._name, k]))
14 | self.__dict__[k] = v
15 |
16 | def __repr__(self):
17 | return f'{self._name}'
18 |
19 | def to_json(self):
20 | keys = [k for k in self.__dict__.keys() if not k.startswith('_')]
21 | data = {k: self.__dict__.get(k) for k in keys}
22 | nested = {k: v for k, v in data.items() if not isinstance(v, str)}
23 | if nested:
24 | body = nested.get('body', '')
25 | if body:
26 | keys = [k for k in body.__dict__.keys() if not k.startswith('_')]
27 | contents = {k: body.__dict__.get(k) for k in keys}
28 | else:
29 | contents = copy(body)
30 | data['body'] = contents
31 | return json.dumps(data)
32 |
33 | ORDER_MSG = {'name': '',
34 | 'type': 'ORDER',
35 | 'body': {'action': '',
36 | 'symbol': '',
37 | 'amount': None,
38 | 'indicator': ''}
39 | }
40 |
41 | SELL_MSG = {'name': '',
42 | 'type': 'ORDER',
43 | 'body': {'action': 'SELL',
44 | 'symbol': '',
45 | 'amount': None,
46 | 'indicator': ''}
47 | }
48 | BUY_MSG = {'name': '',
49 | 'type': 'ORDER',
50 | 'body': {'action': 'BUY',
51 | 'symbol': '',
52 | 'amount': None,
53 | 'indicator': ''}
54 | }
55 |
56 | if __name__ == '__main__':
57 | template = {'name': '', 'type': '', 'body': {'action': '', 'symbol': '', 'amount': None}}
58 | message = MessageData(template)
59 | message.name = 'master'
60 | message.type = 'order'
61 | message.body.action = 'BUY'
62 | message.body.symbol = 'GOOG'
63 | message.body.amount = 100
64 | print(message.to_json())
--------------------------------------------------------------------------------
/RL-Binance/model.py:
--------------------------------------------------------------------------------
1 | #================================================================
2 | #
3 | # File name : model.py
4 | # Author : PyLessons
5 | # Created date: 2021-01-13
6 | # Website : https://pylessons.com/
7 | # GitHub : https://github.com/pythonlessons/RL-Bitcoin-trading-bot
8 | # Description : defined PPO Keras model classes
9 | #
10 | #================================================================
11 | import numpy as np
12 | import tensorflow as tf
13 | from tensorflow.keras.models import Model
14 | from tensorflow.keras.layers import Input, Dense, Flatten, Conv1D, MaxPooling1D#, LSTM
15 | from tensorflow.compat.v1.keras.layers import CuDNNLSTM as LSTM # only for GPU
16 | from tensorflow.keras import backend as K
17 | #tf.config.experimental_run_functions_eagerly(True) # used for debuging and development
18 | tf.compat.v1.disable_eager_execution() # usually using this for fastest performance
19 |
20 | gpus = tf.config.experimental.list_physical_devices('GPU')
21 | if len(gpus) > 0:
22 | print(f'GPUs {gpus}')
23 | try: tf.config.experimental.set_memory_growth(gpus[0], True)
24 | except RuntimeError: pass
25 |
26 | class Shared_Model:
27 | def __init__(self, input_shape, action_space, lr, optimizer, model="Dense"):
28 | X_input = Input(input_shape)
29 | self.action_space = action_space
30 |
31 | # Shared CNN layers:
32 | if model=="CNN":
33 | X = Conv1D(filters=64, kernel_size=6, padding="same", activation="tanh")(X_input)
34 | X = MaxPooling1D(pool_size=2)(X)
35 | X = Conv1D(filters=32, kernel_size=3, padding="same", activation="tanh")(X)
36 | X = MaxPooling1D(pool_size=2)(X)
37 | X = Flatten()(X)
38 |
39 | # Shared LSTM layers:
40 | elif model=="LSTM":
41 | X = LSTM(512, return_sequences=True)(X_input)
42 | X = LSTM(256)(X)
43 |
44 | # Shared Dense layers:
45 | else:
46 | X = Flatten()(X_input)
47 | X = Dense(512, activation="relu")(X)
48 |
49 | # Critic model
50 | V = Dense(512, activation="relu")(X)
51 | V = Dense(256, activation="relu")(V)
52 | V = Dense(64, activation="relu")(V)
53 | value = Dense(1, activation=None)(V)
54 |
55 | self.Critic = Model(inputs=X_input, outputs = value)
56 | self.Critic.compile(loss=self.critic_PPO2_loss, optimizer=optimizer(lr=lr))
57 |
58 | # Actor model
59 | A = Dense(512, activation="relu")(X)
60 | A = Dense(256, activation="relu")(A)
61 | A = Dense(64, activation="relu")(A)
62 | output = Dense(self.action_space, activation="softmax")(A)
63 |
64 | self.Actor = Model(inputs = X_input, outputs = output)
65 | self.Actor.compile(loss=self.ppo_loss, optimizer=optimizer(lr=lr))
66 | #print(self.Actor.summary())
67 |
68 | def ppo_loss(self, y_true, y_pred):
69 | # Defined in https://arxiv.org/abs/1707.06347
70 | advantages, prediction_picks, actions = y_true[:, :1], y_true[:, 1:1+self.action_space], y_true[:, 1+self.action_space:]
71 | LOSS_CLIPPING = 0.2
72 | ENTROPY_LOSS = 0.001
73 |
74 | prob = actions * y_pred
75 | old_prob = actions * prediction_picks
76 |
77 | prob = K.clip(prob, 1e-10, 1.0)
78 | old_prob = K.clip(old_prob, 1e-10, 1.0)
79 |
80 | ratio = K.exp(K.log(prob) - K.log(old_prob))
81 |
82 | p1 = ratio * advantages
83 | p2 = K.clip(ratio, min_value=1 - LOSS_CLIPPING, max_value=1 + LOSS_CLIPPING) * advantages
84 |
85 | actor_loss = -K.mean(K.minimum(p1, p2))
86 |
87 | entropy = -(y_pred * K.log(y_pred + 1e-10))
88 | entropy = ENTROPY_LOSS * K.mean(entropy)
89 |
90 | total_loss = actor_loss - entropy
91 |
92 | return total_loss
93 |
94 | def actor_predict(self, state):
95 | return self.Actor.predict(state)
96 |
97 | def critic_PPO2_loss(self, y_true, y_pred):
98 | value_loss = K.mean((y_true - y_pred) ** 2) # standard PPO loss
99 | return value_loss
100 |
101 | def critic_predict(self, state):
102 | return self.Critic.predict([state, np.zeros((state.shape[0], 1))])
103 |
104 |
105 | class Actor_Model:
106 | def __init__(self, input_shape, action_space, lr, optimizer):
107 | X_input = Input(input_shape)
108 | self.action_space = action_space
109 |
110 | X = Flatten(input_shape=input_shape)(X_input)
111 | X = Dense(512, activation="relu")(X)
112 | X = Dense(256, activation="relu")(X)
113 | X = Dense(64, activation="relu")(X)
114 | output = Dense(self.action_space, activation="softmax")(X)
115 |
116 | self.Actor = Model(inputs = X_input, outputs = output)
117 | self.Actor.compile(loss=self.ppo_loss, optimizer=optimizer(lr=lr))
118 | #print(self.Actor.summary)
119 |
120 | def ppo_loss(self, y_true, y_pred):
121 | # Defined in https://arxiv.org/abs/1707.06347
122 | advantages, prediction_picks, actions = y_true[:, :1], y_true[:, 1:1+self.action_space], y_true[:, 1+self.action_space:]
123 | LOSS_CLIPPING = 0.2
124 | ENTROPY_LOSS = 0.001
125 |
126 | prob = actions * y_pred
127 | old_prob = actions * prediction_picks
128 |
129 | prob = K.clip(prob, 1e-10, 1.0)
130 | old_prob = K.clip(old_prob, 1e-10, 1.0)
131 |
132 | ratio = K.exp(K.log(prob) - K.log(old_prob))
133 |
134 | p1 = ratio * advantages
135 | p2 = K.clip(ratio, min_value=1 - LOSS_CLIPPING, max_value=1 + LOSS_CLIPPING) * advantages
136 |
137 | actor_loss = -K.mean(K.minimum(p1, p2))
138 |
139 | entropy = -(y_pred * K.log(y_pred + 1e-10))
140 | entropy = ENTROPY_LOSS * K.mean(entropy)
141 |
142 | total_loss = actor_loss - entropy
143 |
144 | return total_loss
145 |
146 | def actor_predict(self, state):
147 | return self.Actor.predict(state)
148 |
149 | class Critic_Model:
150 | def __init__(self, input_shape, action_space, lr, optimizer):
151 | X_input = Input(input_shape)
152 |
153 | V = Flatten(input_shape=input_shape)(X_input)
154 | V = Dense(512, activation="relu")(V)
155 | V = Dense(256, activation="relu")(V)
156 | V = Dense(64, activation="relu")(V)
157 | value = Dense(1, activation=None)(V)
158 |
159 | self.Critic = Model(inputs=X_input, outputs = value)
160 | self.Critic.compile(loss=self.critic_PPO2_loss, optimizer=optimizer(lr=lr))
161 |
162 | def critic_PPO2_loss(self, y_true, y_pred):
163 | value_loss = K.mean((y_true - y_pred) ** 2) # standard PPO loss
164 | return value_loss
165 |
166 | def critic_predict(self, state):
167 | return self.Critic.predict([state, np.zeros((state.shape[0], 1))])
168 |
--------------------------------------------------------------------------------
/RL-Binance/multiprocessing_env.py:
--------------------------------------------------------------------------------
1 | #================================================================
2 | #
3 | # File name : multiprocessing_env.py
4 | # Author : PyLessons
5 | # Created date: 2021-02-25
6 | # Website : https://pylessons.com/
7 | # GitHub : https://github.com/pythonlessons/RL-Bitcoin-trading-bot
8 | # Description : functions to train/test multiple custom BTC trading environments
9 | #
10 | #================================================================
11 | from collections import deque
12 | from multiprocessing import Process, Pipe
13 | import numpy as np
14 | from datetime import datetime
15 | import json
16 | from tensorflow.keras.optimizers import Adam
17 |
18 | class Environment(Process):
19 | def __init__(self, env_idx, child_conn, env, training_batch_size, visualize):
20 | super(Environment, self).__init__()
21 | self.env = env
22 | self.env_idx = env_idx
23 | self.child_conn = child_conn
24 | self.training_batch_size = training_batch_size
25 | self.visualize = visualize
26 |
27 | def run(self):
28 | super(Environment, self).run()
29 | state = self.env.reset(env_steps_size = self.training_batch_size)
30 | self.child_conn.send(state)
31 | while True:
32 | reset, net_worth, episode_orders = 0, 0, 0
33 | action = self.child_conn.recv()
34 | if self.env_idx == 0:
35 | self.env.render(self.visualize)
36 | state, reward, done = self.env.step(action)
37 |
38 | if done or self.env.current_step == self.env.end_step:
39 | net_worth = self.env.net_worth
40 | episode_orders = self.env.episode_orders
41 | state = self.env.reset(env_steps_size = self.training_batch_size)
42 | reset = 1
43 |
44 | self.child_conn.send([state, reward, done, reset, net_worth, episode_orders])
45 |
46 | def train_multiprocessing(CustomEnv, agent, train_df, train_df_nomalized, num_worker=4, training_batch_size=500, visualize=False, EPISODES=10000): #original EPISODES:10000
47 | works, parent_conns, child_conns = [], [], []
48 | episode = 0
49 | total_average = deque(maxlen=100) # save recent 100 episodes net worth
50 | best_average = 0 # used to track best average net worth
51 |
52 | for idx in range(num_worker):
53 | parent_conn, child_conn = Pipe()
54 | env = CustomEnv(train_df, train_df_nomalized, lookback_window_size=agent.lookback_window_size)
55 | work = Environment(idx, child_conn, env, training_batch_size, visualize)
56 | work.start()
57 | works.append(work)
58 | parent_conns.append(parent_conn)
59 | child_conns.append(child_conn)
60 |
61 | agent.create_writer(env.initial_balance, env.normalize_value, EPISODES) # create TensorBoard writer
62 |
63 | states = [[] for _ in range(num_worker)]
64 | next_states = [[] for _ in range(num_worker)]
65 | actions = [[] for _ in range(num_worker)]
66 | rewards = [[] for _ in range(num_worker)]
67 | dones = [[] for _ in range(num_worker)]
68 | predictions = [[] for _ in range(num_worker)]
69 |
70 | state = [0 for _ in range(num_worker)]
71 | for worker_id, parent_conn in enumerate(parent_conns):
72 | state[worker_id] = parent_conn.recv()
73 |
74 | while episode < EPISODES:
75 | predictions_list = agent.Actor.actor_predict(np.reshape(state, [num_worker]+[_ for _ in state[0].shape]))
76 | actions_list = [np.random.choice(agent.action_space, p=i) for i in predictions_list]
77 |
78 | for worker_id, parent_conn in enumerate(parent_conns):
79 | parent_conn.send(actions_list[worker_id])
80 | action_onehot = np.zeros(agent.action_space.shape[0])
81 | action_onehot[actions_list[worker_id]] = 1
82 | actions[worker_id].append(action_onehot)
83 | predictions[worker_id].append(predictions_list[worker_id])
84 |
85 | for worker_id, parent_conn in enumerate(parent_conns):
86 | next_state, reward, done, reset, net_worth, episode_orders = parent_conn.recv()
87 | states[worker_id].append(np.expand_dims(state[worker_id], axis=0))
88 | next_states[worker_id].append(np.expand_dims(next_state, axis=0))
89 | rewards[worker_id].append(reward)
90 | dones[worker_id].append(done)
91 | state[worker_id] = next_state
92 |
93 | if reset:
94 | episode += 1
95 | a_loss, c_loss = agent.replay(states[worker_id], actions[worker_id], rewards[worker_id], predictions[worker_id], dones[worker_id], next_states[worker_id])
96 | total_average.append(net_worth)
97 | average = np.average(total_average)
98 |
99 | agent.writer.add_scalar('Data/average net_worth', average, episode)
100 | agent.writer.add_scalar('Data/episode_orders', episode_orders, episode)
101 |
102 | print("episode: {:<5} worker: {:<2} net worth: {:<7.2f} average: {:<7.2f} orders: {}".format(episode, worker_id, net_worth, average, episode_orders))
103 | if episode > len(total_average):
104 | if best_average < average:
105 | best_average = average
106 | print("Saving model")
107 | agent.save(score="{:.2f}".format(best_average), args=[episode, average, episode_orders, a_loss, c_loss])
108 | agent.save()
109 |
110 | states[worker_id] = []
111 | next_states[worker_id] = []
112 | actions[worker_id] = []
113 | rewards[worker_id] = []
114 | dones[worker_id] = []
115 | predictions[worker_id] = []
116 |
117 | # terminating processes after while loop
118 | works.append(work)
119 | for work in works:
120 | work.terminate()
121 | print('TERMINATED:', work)
122 | work.join()
123 |
124 | def test_multiprocessing(CustomEnv, CustomAgent, test_df, test_df_nomalized, num_worker = 4, visualize=True, test_episodes=1000, folder="", name="", comment="", initial_balance=1000, Show_reward=False, Show_indicators=False):
125 | with open(folder+"/Parameters.json", "r") as json_file:
126 | params = json.load(json_file)
127 | if name != "":
128 | params["Actor name"] = f"{name}_Actor.h5"
129 | params["Critic name"] = f"{name}_Critic.h5"
130 | name = params["Actor name"][:-9]
131 |
132 | agent = CustomAgent(lookback_window_size=params["lookback window size"], optimizer=Adam, depth=params["depth"], model=params["model"])
133 |
134 | agent.load(folder, name)
135 | works, parent_conns, child_conns = [], [], []
136 | average_net_worth = 0
137 | average_orders = 0
138 | no_profit_episodes = 0
139 | episode = 0
140 |
141 | for idx in range(num_worker):
142 | parent_conn, child_conn = Pipe()
143 | #env = CustomEnv(test_df, initial_balance=initial_balance, lookback_window_size=agent.lookback_window_size)
144 | env = CustomEnv(df=test_df, df_normalized=test_df_nomalized, initial_balance=initial_balance, lookback_window_size=agent.lookback_window_size)
145 | work = Environment(idx, child_conn, env, training_batch_size=0, visualize=visualize)
146 | work.start()
147 | works.append(work)
148 | parent_conns.append(parent_conn)
149 | child_conns.append(child_conn)
150 |
151 | state = [0 for _ in range(num_worker)]
152 | for worker_id, parent_conn in enumerate(parent_conns):
153 | state[worker_id] = parent_conn.recv()
154 |
155 | while episode < test_episodes:
156 | predictions_list = agent.Actor.actor_predict(np.reshape(state, [num_worker]+[_ for _ in state[0].shape]))
157 | actions_list = [np.random.choice(agent.action_space, p=i) for i in predictions_list]
158 |
159 | for worker_id, parent_conn in enumerate(parent_conns):
160 | parent_conn.send(actions_list[worker_id])
161 |
162 | for worker_id, parent_conn in enumerate(parent_conns):
163 | next_state, reward, done, reset, net_worth, episode_orders = parent_conn.recv()
164 | state[worker_id] = next_state
165 |
166 | if reset:
167 | episode += 1
168 | #print(episode, net_worth, episode_orders)
169 | average_net_worth += net_worth
170 | average_orders += episode_orders
171 | if net_worth < initial_balance: no_profit_episodes += 1 # calculate episode count where we had negative profit through episode
172 | print("episode: {:<5} worker: {:<2} net worth: {:<7.2f} average_net_worth: {:<7.2f} orders: {}".format(episode, worker_id, net_worth, average_net_worth/episode, episode_orders))
173 | if episode == test_episodes: break
174 |
175 | print("No profit episodes: {}".format(no_profit_episodes))
176 | # save test results to test_results.txt file
177 | with open("test_results.txt", "a+") as results:
178 | current_date = datetime.now().strftime('%Y-%m-%d %H:%M')
179 | results.write(f'{current_date}, {name}, test episodes:{test_episodes}')
180 | results.write(f', net worth:{average_net_worth/(episode+1)}, orders per episode:{average_orders/test_episodes}')
181 | results.write(f', no profit episodes:{no_profit_episodes}, model: {agent.model}, comment: {comment}\n')
182 |
183 | # terminating processes after while loop
184 | works.append(work)
185 | for work in works:
186 | work.terminate()
187 | print('TERMINATED:', work)
188 | work.join()
189 |
--------------------------------------------------------------------------------
/RL-Binance/requirements.txt:
--------------------------------------------------------------------------------
1 | numpy
2 | tensorflow==2.3.1
3 | tensorflow-gpu==2.3.1
4 | opencv-python
5 | matplotlib
6 | tensorboardx
7 | pandas
8 | mplfinance
9 | ta
10 | bitfinex-tencars
11 | seaborn
12 |
--------------------------------------------------------------------------------
/RL-Binance/runs/2022_03_26_09_39_Crypto_trader/events.out.tfevents.1648312935.donutpy.local:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DaScient/SuperTrendTradingBot/f8070baa52422d1d5c39b646047a305db295b873/RL-Binance/runs/2022_03_26_09_39_Crypto_trader/events.out.tfevents.1648312935.donutpy.local
--------------------------------------------------------------------------------
/RL-Binance/test.py:
--------------------------------------------------------------------------------
1 | import config
2 | import ccxt
3 | import multiprocessing
4 | from multiprocessing import Process, Pipe, Manager
5 | import threading
6 | import logging
7 | import logging.handlers
8 | import pandas_ta as ta
9 | import json
10 | from copy import copy, deepcopy
11 | import pandas as pd
12 | import numpy as np
13 | import schedule
14 | from message import *
15 | import os
16 | import time
17 |
18 | # just for me
19 | import warnings
20 | warnings.filterwarnings("ignore")
21 |
22 |
23 | rootLogger = logging.getLogger('')
24 | rootLogger.setLevel(logging.INFO)
25 | socketHandler = logging.handlers.SocketHandler('localhost', logging.handlers.DEFAULT_TCP_LOGGING_PORT)
26 | rootLogger.addHandler(socketHandler)
27 |
28 |
29 | def wait_until_complete(manager):
30 | processes = multiprocessing.active_children()
31 | while processes:
32 | if len(processes) == 1 and processes[0].name.startswith('SyncManager'):
33 | manager.shutdown()
34 | processes = multiprocessing.active_children()
35 |
36 |
37 | class BinanceMaster(ccxt.binanceus):
38 |
39 | RSI_PERIOD = 14
40 | RSI_OVERBOUGHT = 100
41 | RSI_OVERSOLD = 30
42 | TEST_SYMBOL = 'DOGE/USDT'
43 |
44 | def __init__(self, account_config=None, master_id=0, duration=500, interval=30):
45 |
46 | self.master_id = master_id
47 | self.connections = dict()
48 | self.ohlcv_limit = 100
49 | self._kill_run = False
50 | self.duration = duration
51 | self.interval = interval
52 |
53 | if account_config is None or not self._validate_config(account_config):
54 | self.config = {}
55 | else:
56 | self.config = account_config
57 |
58 | def _validate_config(self, config_dict):
59 | try:
60 | contains_api_key = 'apiKey' in config_dict.keys()
61 | contains_secret_key = 'secret' in config_dict.keys()
62 | except Exception:
63 | return False
64 | else:
65 | return contains_api_key and contains_secret_key
66 |
67 | def send_message(self, message, close=False):
68 | for name, conn in self.connections.items():
69 | conn.send(message)
70 | if close:
71 | conn.close()
72 |
73 | def _fetch_prices(self):
74 |
75 | data = self.fetch_ohlcv(self.TEST_SYMBOL, timeframe="1h", limit=self.ohlcv_limit)
76 |
77 | # grab elements of every OHLCV list for O,H,L,C prices
78 | opens = np.array([record[1] for record in data])
79 | highs = np.array([record[2] for record in data])
80 | lows = np.array([record[3] for record in data])
81 | closes = np.array([record[4] for record in data])
82 |
83 | return opens, highs, lows, closes
84 |
85 |
86 |
87 | # Calculations and Signal Verification #######################################################
88 |
89 | def calculate_indicator(self, opens, highs, lows, closes):
90 |
91 | # could stay as series for better comp-eff?
92 | df = pd.DataFrame({"open":opens, "high":highs, "low":lows, "close":closes})
93 |
94 | close = df['close'][len(df)-1]
95 |
96 | # conditions passed
97 | ema_33 = df.ta.ema(33)[-1:].reset_index(drop=True)[0]
98 | ema_99 = df.ta.ema(99)[-1:].reset_index(drop=True)[0]
99 | ema_crossover = ema_33 > ema_99
100 |
101 | isa_9 = df.ta.ichimoku()[1]['ISA_9'].tail(1).values[0] # help(ta.ichimoku)
102 | isb_26 = df.ta.ichimoku()[1]['ISB_26'].tail(1).values[0]
103 |
104 | amat = (df.ta.amat()['AMATe_LR_8_21_2'].tail(1).values[0] == 1)
105 |
106 | rsi = df.ta.rsi()[len(df)-1]
107 | rsi_buy = rsi < 35
108 | rsi_sell = rsi > 65
109 |
110 | try:
111 | chop = "{:.2f}".format(df.ta.chop()[len(df.ta.chop())-1])
112 | except RunTimeWarning:
113 | chop = 0
114 |
115 |
116 | #if ((close*1.1 < isa_9) or (close*1.1 < isb_26)) & amat & ema_crossover & rsi_buy: # wants all true
117 | # ind = "BUY"
118 | #elif ((close*1.1 > isa_9) or (close*1.1 > isb_26)) & ~amat & ~ema_crossover & rsi_sell:
119 | # ind = "SELL"
120 |
121 | return isa_9, isb_26, chop, amat, ema_crossover, rsi
122 |
123 |
124 | def _execute_loop(self, status_table=None):
125 | logger = logging.getLogger(f'maestro-{self.master_id}')
126 |
127 | # prices
128 | opens = self._fetch_prices()[0]
129 | highs = self._fetch_prices()[1]
130 | lows = self._fetch_prices()[2]
131 | closes = self._fetch_prices()[3]
132 |
133 | logger.info(f"Close price: {closes[-1:]}")
134 |
135 | # indicators
136 | indicator = self.calculate_indicator(opens, highs, lows, closes)
137 |
138 | logger.info(f"Ichimoku Senkou A9: {indicator[0]}")
139 | logger.info(f"Ichimoku Senkou B26: {indicator[1]}")
140 | logger.info(f"Choppiness Idx: {indicator[2]}%")
141 |
142 | if indicator[3]:
143 | direction = "Up"
144 | else:
145 | direction = "Down"
146 | logger.info(f"Archer MA Trend: {direction}")
147 |
148 | if indicator[4]:
149 | cross = "Below"
150 | else:
151 | cross = "Above"
152 |
153 | logger.info(f"EMA Crossover 33_99: {cross}")
154 |
155 | logger.info(f"RSI: {indicator[5]}")
156 |
157 | #logger.info(f"Indicator: {indicator[0]}")
158 |
159 | logger.info("------------------------------")
160 |
161 |
162 | #message = MessageData(ORDER_MSG)
163 | #message.name = f'maestro-{self.master_id}'
164 | #message.body.symbol = self.TEST_SYMBOL
165 | #message.body.indicator = 'RSI'
166 |
167 | # messenger
168 | #if rsi > self.RSI_OVERBOUGHT:
169 | # message.body.action = 'SELL'
170 | # self.send_message(message.to_json())
171 | #elif rsi < self.RSI_OVERSOLD:
172 | # message.body.action = 'BUY'
173 | # self.send_message(message.to_json())
174 | #else:
175 | # logger.info('RSI ACTION: NONE')
176 |
177 |
178 |
179 | self.log_status_table(status_table)
180 | #
181 | # End of Calculations and Signal Verification
182 |
183 | def run(self, connections, status_table):
184 | super().__init__(self.config)
185 | self.connections = connections
186 | self._pid = os.getpid()
187 | status_table[self._pid] = 'up'
188 |
189 | timer = threading.Thread(target=self._timer_thread, daemon=False)
190 | timer.start()
191 |
192 | schedule.every(self.interval).seconds.do(self._execute_loop, status_table=status_table).tag('indicator')
193 |
194 | while True:
195 | schedule.run_pending()
196 | if self._kill_run:
197 | self.send_message('END TRADING', close=True)
198 | schedule.clear('indicator')
199 | break
200 |
201 | status_table[self._pid] = 'down'
202 | self.log_status_table(status_table)
203 |
204 | def _timer_thread(self):
205 | time.sleep(self.duration)
206 | self._kill_run = True
207 |
208 | def log_status_table(self, status_table):
209 | logger = logging.getLogger(f'maestro-{self.master_id}-stat')
210 | try:
211 | d = dict(status_table)
212 | except Exception as e:
213 | logger.info(str(e))
214 | else:
215 | logger.info(json.dumps(d))
216 |
217 |
218 | class BinanceTrader(ccxt.binanceus):
219 |
220 | def __init__(self, name, user_config=None):
221 |
222 | self.user_name = name
223 |
224 | if user_config is None or not self._validate_config(user_config):
225 | self.config = {}
226 | else:
227 | self.config = user_config
228 |
229 | def _validate_config(self, config_dict):
230 | try:
231 | contains_api_key = 'apiKey' in config_dict.keys()
232 | contains_secret_key = 'secret' in config_dict.keys()
233 | except Exception:
234 | return False
235 | else:
236 | return contains_api_key and contains_secret_key
237 |
238 | def get_user_name(self):
239 | return self.user_name
240 |
241 | def recv_message(self, conn):
242 | logger = logging.getLogger(f'{self.get_user_name()}')
243 | while True:
244 | message = conn.recv()
245 | logger.info(message)
246 | if message == 'END TRADING':
247 | conn.close()
248 | break
249 |
250 | def run(self, conn, status_table):
251 | super().__init__(self.config)
252 | self._pid = os.getpid()
253 | status_table[self._pid] = 'up'
254 | self.recv_message(conn)
255 | status_table[self._pid] = 'down'
256 | self.log_status_table(status_table)
257 |
258 | def log_status_table(self, status_table):
259 | logger = logging.getLogger(f'{self.get_user_name()}-stat')
260 | try:
261 | d = dict(status_table)
262 | except Exception as e:
263 | logger.info(str(e))
264 | else:
265 | logger.info(json.dumps(d))
266 |
267 |
268 | if __name__ == '__main__':
269 |
270 | logging.info('\n\nstarting log')
271 | group = ['trader1']
272 | master_connections = dict()
273 | traders = []
274 |
275 | manager = Manager()
276 | status_table = manager.dict()
277 |
278 | for name in group:
279 | parent_conn, child_conn = Pipe(duplex=True)
280 | master_connections[name] = parent_conn
281 | trader = BinanceTrader(name)
282 | p = Process(target=trader.run, args=(child_conn, status_table), daemon=False)
283 | traders.append(p)
284 |
285 | master_config = {'apiKey': config.apiKey,
286 | 'secret': config.secret,
287 | 'enableRateLimit': True,
288 | 'options' : {'adjustForTimeDifference': True}}
289 |
290 | master = BinanceMaster(account_config=master_config)
291 | p = Process(target=master.run, args=(master_connections, status_table), daemon=False)
292 | p.start()
293 |
294 | for trader in traders:
295 | trader.start()
296 |
297 | wait_until_complete(manager)
--------------------------------------------------------------------------------
/Reinforced Learning for Crypto Trading:
--------------------------------------------------------------------------------
1 | {"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[],"dockerImageVersionId":30822,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"source":" ","metadata":{},"cell_type":"markdown"},{"cell_type":"markdown","source":"# [@donutz.ai](https://donutz.ai)\n\nCreating a Python script that integrates reinforcement learning, machine learning ensembles, and cryptocurrency trading using SHIB on a minute-by-minute basis can be complex, especially if the goal is to build a profitable and interactive system. Here's a basic outline and script that:\n- Applies Reinforcement Learning (RL) for trading (based on our [SuperTrend Trading Bot Project - 2020](https://github.com/DaScient/SuperTrendTradingBot/)).\n- Incorporates Machine Learning Ensembles for improved trading decisions.\n- Demonstrates how this can be gamified, adds user incentives, and provides user tier incentives for subscribing to higher-level analysis.\n\nThis script is designed to work with Kaggle GPU environments. It assumes you are already familiar with using Binance API, data preprocessing, and RL setup.","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19"}},{"cell_type":"code","source":"# install Required Packages\nfrom IPython.display import clear_output\n!pip install numpy pandas tensorflow keras scikit-learn gym plotly\nclear_output()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-06T05:44:24.314063Z","iopub.execute_input":"2025-01-06T05:44:24.314346Z","iopub.status.idle":"2025-01-06T05:44:28.823634Z","shell.execute_reply.started":"2025-01-06T05:44:24.314313Z","shell.execute_reply":"2025-01-06T05:44:28.822671Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# script","metadata":{}},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport random\nimport gym\nfrom sklearn.ensemble import RandomForestClassifier\nimport matplotlib.pyplot as plt\nimport plotly.express as px\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense\n\n# Secret message for the user (δφ = Delta Phi)\ndef secret_message():\n print(\"Welcome to the delta φ trading bot! Keep learning, stay profitable!\")\n print(\"If you're subscribed to a higher tier, the analysis is deeper, and profits greater.\")\n print(\"Unlock advanced strategies and become a master trader!\")\n\n# Define the environment for Reinforcement Learning\nclass TradingEnvironment(gym.Env):\n def __init__(self, df):\n super(TradingEnvironment, self).__init__()\n self.df = df\n self.current_step = 0\n self.balance = 10000 # Starting balance in USD\n self.shares_held = 0\n self.net_worth = self.balance\n self.action_space = gym.spaces.Discrete(3) # 3 actions: 0 = Buy, 1 = Sell, 2 = Hold\n self.observation_space = gym.spaces.Box(low=0, high=1, shape=(5,), dtype=np.float32) # Adjusted for 5 features\n\n def reset(self):\n self.current_step = 0\n self.balance = 10000\n self.shares_held = 0\n self.net_worth = self.balance\n # Return only the relevant state features, excluding timestamp/epoch_time\n return self.df.iloc[self.current_step][['open', 'high', 'low', 'close', 'volume']].values\n\n def step(self, action):\n self.current_step += 1\n if self.current_step >= len(self.df) - 1:\n done = True\n else:\n done = False\n\n prev_balance = self.balance\n prev_net_worth = self.net_worth\n\n current_price = self.df.iloc[self.current_step]['close']\n reward = 0\n\n if action == 0: # Buy\n if self.balance >= current_price:\n self.shares_held += 1\n self.balance -= current_price\n elif action == 1: # Sell\n if self.shares_held > 0:\n self.shares_held -= 1\n self.balance += current_price\n elif action == 2: # Hold\n pass\n\n self.net_worth = self.balance + self.shares_held * current_price\n reward = self.net_worth - prev_net_worth\n\n return self.df.iloc[self.current_step][['open', 'high', 'low', 'close', 'volume']].values, reward, done, {}\n\n# Load and preprocess SHIB data from the provided CSV link\ndef load_data():\n url = 'https://www.cryptodatadownload.com/cdd/Binance_SHIBUSDT_1h.csv'\n df = pd.read_csv(url, header=1)\n \n # Convert Timestamp to epoch time (seconds since 1970)\n df['timestamp'] = pd.to_datetime(df['Date'])\n df['epoch_time'] = df['timestamp'].astype(np.int64) // 10**9 # Convert to seconds\n \n # Use 'epoch_time' instead of 'timestamp' for the model\n df = df[['epoch_time', 'Open', 'High', 'Low', 'Close', 'Volume SHIB']].copy()\n df.rename(columns={'Open': 'open', 'High': 'high', 'Low': 'low', 'Close': 'close', 'Volume SHIB': 'volume'}, inplace=True)\n \n return df\n\n# Training Model: Reinforcement Learning (Deep Q-Learning)\nclass DQNAgent:\n def __init__(self, state_size, action_size):\n self.state_size = state_size\n self.action_size = action_size\n self.memory = []\n self.gamma = 0.95 # Discount factor\n self.epsilon = 1.0 # Exploration rate\n self.epsilon_min = 0.01\n self.epsilon_decay = 0.995\n self.model = self.build_model()\n\n def build_model(self):\n model = Sequential()\n model.add(Dense(24, input_dim=self.state_size, activation='relu'))\n model.add(Dense(24, activation='relu'))\n model.add(Dense(self.action_size, activation='linear'))\n model.compile(loss='mse', optimizer=tf.keras.optimizers.Adam(learning_rate=0.001))\n return model\n\n def act(self, state):\n if np.random.rand() <= self.epsilon:\n return random.randrange(self.action_size)\n act_values = self.model.predict(state)\n return np.argmax(act_values[0])\n\n def remember(self, state, action, reward, next_state, done):\n self.memory.append((state, action, reward, next_state, done))\n\n def replay(self, batch_size):\n if len(self.memory) < batch_size:\n return\n batch = random.sample(self.memory, batch_size)\n for state, action, reward, next_state, done in batch:\n target = reward\n if not done:\n target = reward + self.gamma * np.amax(self.model.predict(next_state)[0])\n target_f = self.model.predict(state)\n target_f[0][action] = target\n self.model.fit(state, target_f, epochs=1, verbose=0)\n if self.epsilon > self.epsilon_min:\n self.epsilon *= self.epsilon_decay\n\n# Main script for training the agent\ndef train_trading_bot():\n df = load_data()\n env = TradingEnvironment(df)\n agent = DQNAgent(state_size=5, action_size=3) # We now have 5 state variables (after excluding epoch_time)\n episodes = 1000\n batch_size = 32\n\n for e in range(episodes):\n state = env.reset()\n state = np.reshape(state, [1, 5]) # Adjusted shape after removing timestamp\n done = False\n while not done:\n action = agent.act(state)\n next_state, reward, done, _ = env.step(action)\n next_state = np.reshape(next_state, [1, 5]) # Adjusted shape\n agent.remember(state, action, reward, next_state, done)\n state = next_state\n agent.replay(batch_size)\n\n if e % 100 == 0:\n print(f\"Episode {e}/{episodes} completed\")\n\n # Secret message\n secret_message()\n\n# Machine Learning Ensemble: Random Forest for predictions (optional enhancement)\ndef ensemble_model(df):\n features = ['open', 'high', 'low', 'volume'] # Add more features as needed\n X = df[features]\n y = df['close'] # Target: Predicting the closing price\n\n model = RandomForestClassifier(n_estimators=100, random_state=42)\n model.fit(X, y)\n \n # Prediction (for testing purposes)\n predictions = model.predict(X)\n return predictions\n\n# Plotting and user incentive: (spunky, fun, interactive chart)\ndef plot_results(df):\n fig = px.line(df, x='timestamp', y=['close'], title=\"SHIB Price Analysis\")\n fig.update_layout(template=\"plotly_dark\", title=\"SHIB Price Movement\")\n fig.show()\n\n# Run the bot (for Kaggle, this will work with GPU enabled)\ntrain_trading_bot()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-06T05:44:28.824843Z","iopub.execute_input":"2025-01-06T05:44:28.825111Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### Setup Instructions:\n- Install Dependencies: Install the necessary libraries:\npip install numpy pandas tensorflow keras scikit-learn gym plotly matplotlib\n- Data Fetching: The script uses pandas to load the SHIB data from the CSV file available via the provided URL (https://www.cryptodatadownload.com/cdd/Binance_SHIBUSDT_1h.csv). Ensure you have internet access for the data fetching.\n- Run the Script: This can be run in any Python environment (Jupyter Notebook, Google Colab, local Python setup). The script will train the agent and display the results of the trading bot as it learns. The plot will be interactive, and a secret message will be printed periodically.\n- Secret Messages:\nThe script prints fun, gamified secret messages, e.g., “Welcome to the delta φ trading bot! Keep learning, stay profitable!” and \"Unlock advanced strategies and become a master trader.\" These are designed to motivate users and encourage engagement.","metadata":{}},{"cell_type":"code","source":"# en fin","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}
--------------------------------------------------------------------------------
/Robinhood Trading Bot/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DaScient/SuperTrendTradingBot/f8070baa52422d1d5c39b646047a305db295b873/Robinhood Trading Bot/.DS_Store
--------------------------------------------------------------------------------
/Robinhood Trading Bot/.ipynb_checkpoints/config-checkpoint.py:
--------------------------------------------------------------------------------
1 | #KEEP SAFE
2 | rh_username = ''
3 | rh_password = ''
4 |
--------------------------------------------------------------------------------
/Robinhood Trading Bot/.ipynb_checkpoints/marquee_robin_bot-checkpoint.py:
--------------------------------------------------------------------------------
1 | import schedule,warnings,time,ast,config
2 | warnings.filterwarnings('ignore')
3 | from dateutil.tz import tzlocal
4 | from datetime import datetime
5 | from random import randint
6 | import robin_stocks as r
7 | from random import seed
8 | import pandas as pd
9 | import numpy as np
10 |
11 | #Robinhood login (ONLY NEED TO RUN THIS PART ONCE)
12 | login = r.authentication.login(username=config.rh_username,password=config.rh_password,store_session=True)
13 | access_token=login['access_token']
14 | token_type=login['token_type']
15 |
16 | # Analysis & decision making. This part could be extracted out into it's own class.
17 | # Set user variables
18 | tick = "DOGE"#input("Insert ticker: ")
19 | interval = "5minute"#input("Insert desired time intervals: ")
20 | span = "day"
21 | volatility=0.5555555#float(input("Volatility rate: "))
22 |
23 | # Supertrend
24 | # (TR) The true range indicator is taken as the greatest of the following: current high less the current low; the absolute value of the current high less the previous close; and the absolute value of the current low less the previous close
25 | def tr(data):
26 | data['previous_close'] = data['close'].shift(1)
27 | data['high-low'] = abs(data['high'] - data['low'])
28 | data['high-pc'] = abs(data['high'] - data['previous_close'])
29 | data['low-pc'] = abs(data['low'] - data['previous_close'])
30 | tr = data[['high-low','high-pc','low-pc']].max(axis=1)
31 | return tr
32 |
33 | #TR rolling average
34 | def atr(data, period):
35 | data['tr'] = tr(data)
36 | atr = data['tr'].rolling(period).mean()
37 | return atr
38 |
39 | # https://www.tradingfuel.com/supertrend-indicator-formula-and-calculation/ #It's important to treat the atr_multiplier as a variable. See supertrend_visualizer_parquet.py to see how atr_mult affects indication. Volatility rate varies from 0.0001 - 3. Smaller numbers for 1m intervals. Larger number for day or swing trades.
40 | def supertrend(df, period = 7, atr_multiplier = volatility):
41 | hl2 = (df['high'] + df['low'])/2
42 | df['atr'] = atr(df, period)
43 | df['upperband'] = hl2 + (atr_multiplier * df['atr'])
44 | df['lowerband'] = hl2 - (atr_multiplier * df['atr'])
45 | df['in_uptrend'] = True
46 | for current in range(1, len(df.index)):
47 | previous = current - 1
48 | if df['close'][current] > df['upperband'][previous]:
49 | df['in_uptrend'][current] = True
50 | elif df['close'][current] < df['lowerband'][previous]:
51 | df['in_uptrend'][current] = False
52 | else:
53 | df['in_uptrend'][current] = df['in_uptrend'][previous]
54 | if (df['in_uptrend'][current]) and (df['lowerband'][current] < df['lowerband'][previous]):
55 | df['lowerband'][current] = df['lowerband'][previous]
56 | if not df['in_uptrend'][current] and df['upperband'][current] > df['upperband'][previous]:
57 | df['upperband'][current] = df['upperband'][previous]
58 | return df
59 |
60 |
61 | #Signal
62 | def check_buy_sell_signals(df):
63 | global tick,interval,span
64 | print("Analyzing",tick,"data... ")
65 | print(df.tail(3)[['timestamp','close','volume','in_uptrend']])
66 | last_row_index = len(df.index) - 1
67 | previous_row_index = last_row_index - 1
68 | # check for uptrend - if in_uptrend goes from False to True
69 | if not df['in_uptrend'][previous_row_index] and df['in_uptrend'][last_row_index]:
70 |
71 | # no executions, just signals.
72 | print("\n############################")
73 | print("# Changed to uptrend - Buy #")
74 | print("############################")
75 |
76 | # check for downtrend - if in_uptrend goes from True to False
77 | if df['in_uptrend'][previous_row_index] and not df['in_uptrend'][last_row_index]:
78 |
79 | # no executions, just signals.
80 | print("\n###############################")
81 | print("# Changed to downtrend - Sell #")
82 | print("###############################")
83 | # run_bot()
84 | #Execution
85 | def run_bot():
86 | print(f"\n{datetime.now(tzlocal()).isoformat()}")
87 | print("\nTimeframe:",timeframe,"\n")
88 |
89 | # pulls in rh ticker data
90 | df=pd.DataFrame.from_dict(r.crypto.get_crypto_historicals(tick, interval=interval, span=span, bounds='24_7', info=None))
91 | df['timestamp']=pd.to_datetime(df['begins_at'], format='%Y-%m-%d').dt.tz_localize(None)
92 | df['open'] = df.apply(lambda x : float(x['open_price']),axis=1)
93 | df['high'] = df.apply(lambda x : float(x['high_price']),axis=1)
94 | df['low'] = df.apply(lambda x : float(x['low_price']),axis=1)
95 | df['close'] = df.apply(lambda x : float(x['close_price']),axis=1)
96 | df=df.drop(columns=['open_price','high_price','low_price'])
97 | df=df[:-1][['timestamp','open','high','low','close','volume']]
98 |
99 | df.tail(10)
100 |
101 | supertrend_data = supertrend(df)
102 | check_buy_sell_signals(supertrend_data)
103 |
104 | #print("Minimum sell price:",min_sell_price,", Order size:",order_size)
105 |
106 | """
107 | Run Bot, To the Moon
108 | """
109 | schedule.every(5).minutes.do(run_bot)
110 | while True:
111 | schedule.run_pending()
112 | time.sleep(0)
113 |
114 |
115 |
116 |
--------------------------------------------------------------------------------
/Robinhood Trading Bot/.ipynb_checkpoints/robin_bot_v1-checkpoint.py:
--------------------------------------------------------------------------------
1 | import schedule,warnings,time,ast,config
2 | warnings.filterwarnings('ignore')
3 | from dateutil.tz import tzlocal
4 | from datetime import datetime
5 | from random import randint
6 | import robin_stocks as r
7 | from random import seed
8 | import pandas as pd
9 | import numpy as np
10 |
11 | #Robinhood login (ONLY NEED TO RUN THIS PART ONCE)
12 | login = r.authentication.login(username=config.rh_username,password=config.rh_password,store_session=True)
13 | access_token=login['access_token']
14 | token_type=login['token_type']
15 |
16 | #Supertrend formula
17 | def tr(data):
18 | data['previous_close'] = data['close'].shift(1)
19 | data['high-low'] = abs(data['high'] - data['low'])
20 | data['high-pc'] = abs(data['high'] - data['previous_close'])
21 | data['low-pc'] = abs(data['low'] - data['previous_close'])
22 | tr = data[['high-low', 'high-pc', 'low-pc']].max(axis=1)
23 | return tr
24 | def atr(data, period):
25 | data['tr'] = tr(data)
26 | atr = data['tr'].rolling(period).mean()
27 | return atr
28 | def supertrend(df, period=7, atr_multiplier=3):
29 | hl2 = (df['high'] + df['low']) / 2
30 | df['atr'] = atr(df, period)
31 | df['upperband'] = hl2 + (atr_multiplier * df['atr'])
32 | df['lowerband'] = hl2 - (atr_multiplier * df['atr'])
33 | df['in_uptrend'] = True
34 | for current in range(1, len(df.index)):
35 | previous = current - 1
36 | if df['close'][current] > df['upperband'][previous]:
37 | df['in_uptrend'][current] = True
38 | elif df['close'][current] < df['lowerband'][previous]:
39 | df['in_uptrend'][current] = False
40 | else:
41 | df['in_uptrend'][current] = df['in_uptrend'][previous]
42 | if df['in_uptrend'][current] and df['lowerband'][current] < df['lowerband'][previous]:
43 | df['lowerband'][current] = df['lowerband'][previous]
44 | if not df['in_uptrend'][current] and df['upperband'][current] > df['upperband'][previous]:
45 | df['upperband'][current] = df['upperband'][previous]
46 | return df
47 | #Parameters
48 | name="Don"#input("Enter name: ")
49 | ticker="DOGE"#input("Insert ticker: ").upper()
50 | timeframe="5minute"#input('Interval must be "15second","5minute","10minute","hour","day",or "week": ')
51 | span="day"#input('Span must be "hour","day","week","month","3month","year",or "5year": ')
52 | order_size = 200#float(input("Order size in "+tick+": "))
53 | in_position = False#ast.literal_eval(input("Do not accumulate until next buy signal? - True/False: ").capitalize())
54 | min_sell_price=0.24#float(input("Minimum sell price: "))
55 | markup=1+float(0.03)#float(input("Enter percentage of desired markup: %"))/100
56 |
57 | #Signal
58 | def check_buy_sell_signals(df):
59 | global in_position,order_size,ticker,timeframe,trade_amount,min_sell_price,markup
60 | print("Analyzing",ticker,"data... ")
61 | print(df.tail(3)[['timestamp','close','volume','in_uptrend']])
62 | last_row_index = len(df.index) - 1
63 | previous_row_index = last_row_index - 1
64 | if not df['in_uptrend'][previous_row_index] and df['in_uptrend'][last_row_index]:
65 | print("Changed to uptrend. Attempting purchase.")
66 | if not in_position:
67 | order = r.order_buy_crypto_limit(ticker,order_size,r.get_crypto_quote(ticker, info=None)["mark_price"], timeInForce='gtc')
68 | print('Status:'+order['state'],
69 | 'Price:'+float(order['price']),
70 | 'Quantity:'+float(order['quantity']),
71 | 'Type:'+order['side'])
72 | order_id = order["id"]
73 | print("Order state:",r.get_crypto_order_info(order_id)['state'])
74 | if r.get_crypto_order_info(order_id)['state']=='filled':
75 | min_sell_price = float(order['price'])
76 | in_position = True
77 | print("Purchased.")
78 | else:
79 | print("Previous order: ",order_id,"still not filled.")
80 | else:
81 | print("Already in desired trading position, no task.")
82 | if df['in_uptrend'][previous_row_index] and not df['in_uptrend'][last_row_index]:
83 | price = float(r.get_crypto_quote("DOGE", info=None)['low_price'])#curent low price
84 | print("Changed to downtrend. Attempting sale.")
85 | if in_position and price > min_sell_price:
86 | order_sell = r.order_sell_crypto_limit(ticker, order_size,min_sell_price*markup, timeInForce='gtc')
87 | print('Status:'+order_sell['state'],
88 | 'Price:'+float(order_sell['price']),
89 | 'Quantity:'+float(order_sell['quantity']),
90 | 'Type:'+order_sell['side'])
91 | order_id_sell = order_sell["id"]
92 | print("Order state:",r.get_crypto_order_info(order_id_sell)['state'])
93 | if r.get_crypto_order_info(order_id_sell)['state']=='filled':
94 | in_position = False
95 | print("Order ID:",order_id_sell,"sold.")
96 | else:
97 | print("Previous order: ",order_id_sell,"still not filled.")
98 | else:
99 | print("Did not find opportunity to sell, no task.")
100 | #Execution
101 | def run_bot():
102 | print(f"\n{datetime.now(tzlocal()).isoformat()}")
103 | print("In position:", in_position,";\nTimeframe: ",timeframe,"\n")
104 |
105 | # pulls in rh ticker data
106 | df=pd.DataFrame.from_dict(r.crypto.get_crypto_historicals("DOGE", interval='5minute', span='day', bounds='24_7', info=None))
107 | df['timestamp']=pd.to_datetime(df['begins_at'], format='%Y-%m-%d').dt.tz_localize(None)
108 | df['open'] = df.apply(lambda x : float(x['open_price']),axis=1)
109 | df['high'] = df.apply(lambda x : float(x['high_price']),axis=1)
110 | df['low'] = df.apply(lambda x : float(x['low_price']),axis=1)
111 | df['close'] = df.apply(lambda x : float(x['close_price']),axis=1)
112 | df=df.drop(columns=['open_price','close_price','high_price','low_price'])
113 | df=df[:-1][['timestamp','open','high','low','close','volume']]
114 |
115 | supertrend_data = supertrend(df)
116 | check_buy_sell_signals(supertrend_data)
117 |
118 | print("Minimum sell price:",min_sell_price,", Order size:",order_size)
119 | print(name,"'s profit margin set to:",markup,"%")
120 | schedule.every(randint(42,299)).seconds.do(run_bot)
121 | while True:
122 | schedule.run_pending()
123 | time.sleep(1)
--------------------------------------------------------------------------------
/Robinhood Trading Bot/.ipynb_checkpoints/robin_supertrend_visualizer-checkpoint.py:
--------------------------------------------------------------------------------
1 | import schedule,warnings,time,ast,config
2 | warnings.filterwarnings('ignore')
3 | import matplotlib.pyplot as plt
4 | from dateutil.tz import tzlocal
5 | from datetime import datetime
6 | from random import randint
7 | import robin_stocks as r
8 | from random import seed
9 | import seaborn as sns
10 | from PIL import Image
11 | import pandas as pd
12 | import numpy as np
13 |
14 |
15 | #Robinhood login
16 | login = r.authentication.login(username=config.rh_username,password=config.rh_password,store_session=True)
17 | access_token=login['access_token']
18 | token_type=login['token_type']
19 |
20 |
21 | #Doge data
22 | ticker=input("Enter crypto ticker: ").upper()
23 | timeframe=intput('Interval must be "15second","5minute","10minute","hour","day",or "week": ')
24 | span = input('Span must be "hour","day","week","month","3month","year",or "5year": ')
25 |
26 | df=pd.DataFrame.from_dict(r.crypto.get_crypto_historicals(ticker, interval=timeframe, span=span, bounds='24_7', info=None))
27 | df['timestamp']=pd.to_datetime(df['begins_at'], format='%Y-%m-%d').dt.tz_localize(None)
28 | df['open'] = df.apply(lambda x : float(x['open_price']),axis=1)
29 | df['high'] = df.apply(lambda x : float(x['high_price']),axis=1)
30 | df['low'] = df.apply(lambda x : float(x['low_price']),axis=1)
31 | df['close'] = df.apply(lambda x : float(x['close_price']),axis=1)
32 | df=df.drop(columns=['open_price','close_price','high_price','low_price'])
33 | df=df[:-25][['timestamp','open','high','low','close','volume']]
34 | supertrend_data = supertrend(df)
35 |
36 | #Set plot() params
37 | fig, ax = plt.subplots(figsize=(20, 8))
38 |
39 | #Signals 1.1
40 | xcoords_sell = supertrend_data[supertrend_data.in_uptrend == False].index
41 | xcoords_buy = supertrend_data[supertrend_data.in_uptrend == True].index
42 |
43 | #Signals 1.2
44 | for xc in xcoords_sell:
45 | plt.axvline(x=xc,c='r')
46 | for xc in xcoords_buy:
47 | plt.axvline(x=xc,c='g')
48 |
49 | #Plot close price
50 | ax.plot(supertrend_data.close, color = 'black', label = 'Line 1')
51 |
52 | #Plot bollinger bands
53 | #ax.plot(supertrend_data.upperband, color = 'lime', label = 'upperband')
54 | #ax.plot(supertrend_data.lowerband, color = 'pink', label = 'lowerband')
55 |
56 | #PLot outputs
57 | ax.legend(loc = 'upper left')
58 | plt.savefig(f'supertrend_visual_{ticker}.jpg')
59 | plt.show()
--------------------------------------------------------------------------------
/Robinhood Trading Bot/__pycache__/config.cpython-38.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DaScient/SuperTrendTradingBot/f8070baa52422d1d5c39b646047a305db295b873/Robinhood Trading Bot/__pycache__/config.cpython-38.pyc
--------------------------------------------------------------------------------
/Robinhood Trading Bot/config.py:
--------------------------------------------------------------------------------
1 | #KEEP SAFE
2 | rh_username = ''
3 | rh_password = ''
4 |
--------------------------------------------------------------------------------
/Robinhood Trading Bot/get_balance.py:
--------------------------------------------------------------------------------
1 | ###############################################
2 | # safemode -
3 | # does not allow for sell at loss. expect longer trade activity intervals.
4 | ###############################################
5 |
6 | from IPython.display import clear_output
7 | import schedule,warnings,time,ast,config
8 | warnings.filterwarnings('ignore')
9 | from dateutil.tz import tzlocal
10 | from datetime import datetime
11 | from random import randint
12 | import robin_stocks as r
13 | from random import seed
14 | import pandas as pd
15 | import numpy as np
16 | from rich import print, pretty
17 | pretty.install()
18 |
19 | # {login} (ONLY NEED TO RUN THIS PART ONCE)
20 | user = "user1"
21 |
22 | login = r.authentication.login(username=config.rh_username,password=config.rh_password,store_session=True)
23 |
24 | access_token=login['access_token']
25 | token_type=login['token_type']
26 | # {end of login}
27 |
28 | print()
29 | bal = pd.DataFrame(r.crypto.get_crypto_positions()).sort_values('quantity',ascending=False)
30 | bal['quantity'] = pd.to_numeric(bal['quantity'])
31 | bal['quantity_available'] = pd.to_numeric(bal['quantity_available'])
32 | bal['asset'] = bal['currency'].apply(lambda x: x['code'])
33 | bal['name'] = bal['currency'].apply(lambda x: x['name'])
34 | bal = bal[bal.quantity > 0].reset_index(drop=True)
35 |
36 | print(bal[['asset', 'quantity', 'quantity_available']])
37 |
38 | profile = r.profiles.load_account_profile()
39 | deno_bal = pd.to_numeric(profile['crypto_buying_power'])
40 | print("Crypto buying power: ", deno_bal)
41 | print()
--------------------------------------------------------------------------------
/Robinhood Trading Bot/marquee_robin_bot.py:
--------------------------------------------------------------------------------
1 | import schedule,warnings,time,ast,config
2 | warnings.filterwarnings('ignore')
3 | from dateutil.tz import tzlocal
4 | from datetime import datetime
5 | from random import randint
6 | import robin_stocks as r
7 | from random import seed
8 | import pandas as pd
9 | import numpy as np
10 |
11 | #Robinhood login (ONLY NEED TO RUN THIS PART ONCE)
12 | login = r.authentication.login(username=config.rh_username,password=config.rh_password,store_session=True)
13 | access_token=login['access_token']
14 | token_type=login['token_type']
15 |
16 | # Analysis & decision making. This part could be extracted out into it's own class.
17 | # Set user variables
18 | tick = "DOGE"#input("Insert ticker: ")
19 | interval = "5minute"#input("Insert desired time intervals: ")
20 | span = "day"
21 | volatility=0.5555555#float(input("Volatility rate: "))
22 |
23 | # Supertrend
24 | # (TR) The true range indicator is taken as the greatest of the following: current high less the current low; the absolute value of the current high less the previous close; and the absolute value of the current low less the previous close
25 | def tr(data):
26 | data['previous_close'] = data['close'].shift(1)
27 | data['high-low'] = abs(data['high'] - data['low'])
28 | data['high-pc'] = abs(data['high'] - data['previous_close'])
29 | data['low-pc'] = abs(data['low'] - data['previous_close'])
30 | tr = data[['high-low','high-pc','low-pc']].max(axis=1)
31 | return tr
32 |
33 | #TR rolling average
34 | def atr(data, period):
35 | data['tr'] = tr(data)
36 | atr = data['tr'].rolling(period).mean()
37 | return atr
38 |
39 | # https://www.tradingfuel.com/supertrend-indicator-formula-and-calculation/ #It's important to treat the atr_multiplier as a variable. See supertrend_visualizer_parquet.py to see how atr_mult affects indication. Volatility rate varies from 0.0001 - 3. Smaller numbers for 1m intervals. Larger number for day or swing trades.
40 | def supertrend(df, period = 7, atr_multiplier = volatility):
41 | hl2 = (df['high'] + df['low'])/2
42 | df['atr'] = atr(df, period)
43 | df['upperband'] = hl2 + (atr_multiplier * df['atr'])
44 | df['lowerband'] = hl2 - (atr_multiplier * df['atr'])
45 | df['in_uptrend'] = True
46 | for current in range(1, len(df.index)):
47 | previous = current - 1
48 | if df['close'][current] > df['upperband'][previous]:
49 | df['in_uptrend'][current] = True
50 | elif df['close'][current] < df['lowerband'][previous]:
51 | df['in_uptrend'][current] = False
52 | else:
53 | df['in_uptrend'][current] = df['in_uptrend'][previous]
54 | if (df['in_uptrend'][current]) and (df['lowerband'][current] < df['lowerband'][previous]):
55 | df['lowerband'][current] = df['lowerband'][previous]
56 | if not df['in_uptrend'][current] and df['upperband'][current] > df['upperband'][previous]:
57 | df['upperband'][current] = df['upperband'][previous]
58 | return df
59 |
60 |
61 | #Signal
62 | def check_buy_sell_signals(df):
63 | global tick,interval,span
64 | print("Analyzing",tick,"data... ")
65 | print(df.tail(3)[['timestamp','close','volume','in_uptrend']])
66 | last_row_index = len(df.index) - 1
67 | previous_row_index = last_row_index - 1
68 | # check for uptrend - if in_uptrend goes from False to True
69 | if not df['in_uptrend'][previous_row_index] and df['in_uptrend'][last_row_index]:
70 |
71 | # no executions, just signals.
72 | print("\n############################")
73 | print("# Changed to uptrend - Buy #")
74 | print("############################")
75 |
76 | # check for downtrend - if in_uptrend goes from True to False
77 | if df['in_uptrend'][previous_row_index] and not df['in_uptrend'][last_row_index]:
78 |
79 | # no executions, just signals.
80 | print("\n###############################")
81 | print("# Changed to downtrend - Sell #")
82 | print("###############################")
83 | # run_bot()
84 | #Execution
85 | def run_bot():
86 | print(f"\n{datetime.now(tzlocal()).isoformat()}")
87 | print("\nTimeframe:",timeframe,"\n")
88 |
89 | # pulls in rh ticker data
90 | df=pd.DataFrame.from_dict(r.crypto.get_crypto_historicals(tick, interval=interval, span=span, bounds='24_7', info=None))
91 | df['timestamp']=pd.to_datetime(df['begins_at'], format='%Y-%m-%d').dt.tz_localize(None)
92 | df['open'] = df.apply(lambda x : float(x['open_price']),axis=1)
93 | df['high'] = df.apply(lambda x : float(x['high_price']),axis=1)
94 | df['low'] = df.apply(lambda x : float(x['low_price']),axis=1)
95 | df['close'] = df.apply(lambda x : float(x['close_price']),axis=1)
96 | df=df.drop(columns=['open_price','high_price','low_price'])
97 | df=df[:-1][['timestamp','open','high','low','close','volume']]
98 |
99 | df.tail(10)
100 |
101 | supertrend_data = supertrend(df)
102 | check_buy_sell_signals(supertrend_data)
103 |
104 | #print("Minimum sell price:",min_sell_price,", Order size:",order_size)
105 |
106 | """
107 | Run Bot, To the Moon
108 | """
109 | schedule.every(5).minutes.do(run_bot)
110 | while True:
111 | schedule.run_pending()
112 | time.sleep(0)
113 |
114 |
115 |
116 |
--------------------------------------------------------------------------------
/Robinhood Trading Bot/robin_supertrend_visualizer.py:
--------------------------------------------------------------------------------
1 | import schedule,warnings,time,ast,config
2 | warnings.filterwarnings('ignore')
3 | import matplotlib.pyplot as plt
4 | from dateutil.tz import tzlocal
5 | from datetime import datetime
6 | from random import randint
7 | import robin_stocks as r
8 | from random import seed
9 | import seaborn as sns
10 | from PIL import Image
11 | import pandas as pd
12 | import numpy as np
13 |
14 |
15 | #Robinhood login
16 | login = r.authentication.login(username=config.rh_username,password=config.rh_password,store_session=True)
17 | access_token=login['access_token']
18 | token_type=login['token_type']
19 |
20 |
21 | #Doge data
22 | ticker=input("Enter crypto ticker: ").upper()
23 | timeframe=intput('Interval must be "15second","5minute","10minute","hour","day",or "week": ')
24 | span = input('Span must be "hour","day","week","month","3month","year",or "5year": ')
25 |
26 | df=pd.DataFrame.from_dict(r.crypto.get_crypto_historicals(ticker, interval=timeframe, span=span, bounds='24_7', info=None))
27 | df['timestamp']=pd.to_datetime(df['begins_at'], format='%Y-%m-%d').dt.tz_localize(None)
28 | df['open'] = df.apply(lambda x : float(x['open_price']),axis=1)
29 | df['high'] = df.apply(lambda x : float(x['high_price']),axis=1)
30 | df['low'] = df.apply(lambda x : float(x['low_price']),axis=1)
31 | df['close'] = df.apply(lambda x : float(x['close_price']),axis=1)
32 | df=df.drop(columns=['open_price','close_price','high_price','low_price'])
33 | df=df[:-25][['timestamp','open','high','low','close','volume']]
34 | supertrend_data = supertrend(df)
35 |
36 | #Set plot() params
37 | fig, ax = plt.subplots(figsize=(20, 8))
38 |
39 | #Signals 1.1
40 | xcoords_sell = supertrend_data[supertrend_data.in_uptrend == False].index
41 | xcoords_buy = supertrend_data[supertrend_data.in_uptrend == True].index
42 |
43 | #Signals 1.2
44 | for xc in xcoords_sell:
45 | plt.axvline(x=xc,c='r')
46 | for xc in xcoords_buy:
47 | plt.axvline(x=xc,c='g')
48 |
49 | #Plot close price
50 | ax.plot(supertrend_data.close, color = 'black', label = 'Line 1')
51 |
52 | #Plot bollinger bands
53 | #ax.plot(supertrend_data.upperband, color = 'lime', label = 'upperband')
54 | #ax.plot(supertrend_data.lowerband, color = 'pink', label = 'lowerband')
55 |
56 | #PLot outputs
57 | ax.legend(loc = 'upper left')
58 | plt.savefig(f'supertrend_visual_{ticker}.jpg')
59 | plt.show()
--------------------------------------------------------------------------------
/crypto-forecast-using-statsmodels-varmax.ipynb:
--------------------------------------------------------------------------------
1 | {"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.7.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":196858,"sourceType":"datasetVersion","datasetId":1963}],"dockerImageVersionId":30176,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"source":" ","metadata":{},"cell_type":"markdown"},{"cell_type":"markdown","source":"# Welcome to our Universe\n## [@donutz.ai](www.donutz.ai/#)","metadata":{}},{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n for filename in filenames:\n print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-03-20T00:29:17.47261Z","iopub.execute_input":"2022-03-20T00:29:17.473371Z","iopub.status.idle":"2022-03-20T00:29:17.508896Z","shell.execute_reply.started":"2022-03-20T00:29:17.47327Z","shell.execute_reply":"2022-03-20T00:29:17.508212Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"**Get our data**","metadata":{}},{"cell_type":"code","source":"# bring in data\ndf = pd.read_csv('/kaggle/input/all-crypto-currencies/crypto-markets.csv')\n\n# isolate BTC\ndf = df.loc[df.symbol == 'BTC']\ndf.head()","metadata":{"execution":{"iopub.status.busy":"2022-03-20T00:29:17.552397Z","iopub.execute_input":"2022-03-20T00:29:17.552928Z","iopub.status.idle":"2022-03-20T00:29:20.06257Z","shell.execute_reply.started":"2022-03-20T00:29:17.552894Z","shell.execute_reply":"2022-03-20T00:29:20.061715Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.set_index('date')['close'].tail(500).plot(figsize=(15,4), title='BTC - close')","metadata":{"execution":{"iopub.status.busy":"2022-03-20T00:29:20.064596Z","iopub.execute_input":"2022-03-20T00:29:20.065133Z","iopub.status.idle":"2022-03-20T00:29:20.307588Z","shell.execute_reply.started":"2022-03-20T00:29:20.06509Z","shell.execute_reply":"2022-03-20T00:29:20.306763Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"**Scale data**","metadata":{}},{"cell_type":"code","source":"# Use Scikit-learn to transform with maximum absolute scaling\nfrom sklearn.preprocessing import MinMaxScaler,MaxAbsScaler\n\nscaled_df = df.set_index('date')[['open','high','low','close']]\n\nscaler = MaxAbsScaler()\nscaler.fit(scaled_df)\nscaled = scaler.transform(scaled_df)\nscaled_df = pd.DataFrame(scaled_df, columns=scaled_df.columns)\n\n# use first 1000 days as train\ntrain = scaled_df[:1000]\n\n# simulation window\nwindow = 100 # days look ahead\ntest = scaled_df[1000:1000+window]","metadata":{"execution":{"iopub.status.busy":"2022-03-20T00:29:20.309172Z","iopub.execute_input":"2022-03-20T00:29:20.309652Z","iopub.status.idle":"2022-03-20T00:29:21.248791Z","shell.execute_reply.started":"2022-03-20T00:29:20.309609Z","shell.execute_reply":"2022-03-20T00:29:21.247865Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"We will feed the model with our training data as the first 1000 days.","metadata":{}},{"cell_type":"code","source":"train.tail()","metadata":{"execution":{"iopub.status.busy":"2022-03-20T00:29:21.250516Z","iopub.execute_input":"2022-03-20T00:29:21.25073Z","iopub.status.idle":"2022-03-20T00:29:21.263209Z","shell.execute_reply.started":"2022-03-20T00:29:21.250703Z","shell.execute_reply":"2022-03-20T00:29:21.26223Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Then our predicted model will be compared against the test set, which captures 100 days into our observed future.","metadata":{}},{"cell_type":"code","source":"test.head()","metadata":{"execution":{"iopub.status.busy":"2022-03-20T00:36:23.032566Z","iopub.execute_input":"2022-03-20T00:36:23.032849Z","iopub.status.idle":"2022-03-20T00:36:23.047242Z","shell.execute_reply.started":"2022-03-20T00:36:23.032822Z","shell.execute_reply":"2022-03-20T00:36:23.046351Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"**Initiate VARMAX Modeling**\n\nAs well as, output model summary for each variable [o,h,l,c].","metadata":{}},{"cell_type":"code","source":"# VARMA example\nfrom statsmodels.tsa.statespace.varmax import VARMAX\n\n# contrived dataset\ndata = train[['open','high','low','close']]\n# fit model\nmodel = VARMAX(data, freq = 'D', order=(1,1), seasonal_order=(0, 0, 0, 0),\n mle_regression = True,\n filter_concentrated = True)\nmodel_fit = model.fit(disp=True)\n\n# make prediction\nyhat = model_fit.predict(len(data), len(data))\n\nfrom IPython.display import clear_output\nclear_output()\n\nmodel_fit.summary()","metadata":{"execution":{"iopub.status.busy":"2022-03-20T00:29:21.283485Z","iopub.execute_input":"2022-03-20T00:29:21.28373Z","iopub.status.idle":"2022-03-20T00:29:47.531911Z","shell.execute_reply.started":"2022-03-20T00:29:21.283701Z","shell.execute_reply":"2022-03-20T00:29:47.530947Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# simulate prediction\nmodel_fit.plot_diagnostics(3,figsize=(20,5))","metadata":{"execution":{"iopub.status.busy":"2022-03-20T00:29:47.533074Z","iopub.execute_input":"2022-03-20T00:29:47.533313Z","iopub.status.idle":"2022-03-20T00:29:48.724632Z","shell.execute_reply.started":"2022-03-20T00:29:47.533286Z","shell.execute_reply":"2022-03-20T00:29:48.723773Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# plot\npred = pd.DataFrame()\npred['prediction'] = model_fit.simulate(window).reset_index(drop=True).close\npred['observed'] = test.reset_index(drop=True).close\npred.plot(figsize=(20,5),title='prediction vs observed',color=['blue','black'],style=['--','-'])","metadata":{"execution":{"iopub.status.busy":"2022-03-20T00:29:48.72591Z","iopub.execute_input":"2022-03-20T00:29:48.726149Z","iopub.status.idle":"2022-03-20T00:29:49.018922Z","shell.execute_reply.started":"2022-03-20T00:29:48.726119Z","shell.execute_reply":"2022-03-20T00:29:49.018282Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"**Plot prediction - observed**","metadata":{}},{"cell_type":"code","source":"pred['prediction - observed'] = pred['prediction'] - pred['observed']\npred.plot(figsize=(20,5),title='forecast error',color=['blue','black','green'],style=['--','-',':'])","metadata":{"execution":{"iopub.status.busy":"2022-03-20T00:29:49.020038Z","iopub.execute_input":"2022-03-20T00:29:49.020496Z","iopub.status.idle":"2022-03-20T00:29:49.306973Z","shell.execute_reply.started":"2022-03-20T00:29:49.02046Z","shell.execute_reply":"2022-03-20T00:29:49.30614Z"},"trusted":true},"outputs":[],"execution_count":null}]}
--------------------------------------------------------------------------------
/hello universe!:
--------------------------------------------------------------------------------
1 | {"cells":[{"source":" ","metadata":{},"cell_type":"markdown"},{"cell_type":"code","execution_count":1,"id":"950f061c","metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","execution":{"iopub.execute_input":"2025-02-03T00:40:07.215924Z","iopub.status.busy":"2025-02-03T00:40:07.215506Z","iopub.status.idle":"2025-02-03T00:40:08.190992Z","shell.execute_reply":"2025-02-03T00:40:08.189928Z"},"papermill":{"duration":0.980592,"end_time":"2025-02-03T00:40:08.192959","exception":false,"start_time":"2025-02-03T00:40:07.212367","status":"completed"},"tags":[]},"outputs":[],"source":["# This Python 3 environment comes with many helpful analytics libraries installed\n","# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n","# For example, here's several helpful packages to load\n","\n","import numpy as np # linear algebra\n","import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n","\n","# Input data files are available in the read-only \"../input/\" directory\n","# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n","\n","import os\n","for dirname, _, filenames in os.walk('/kaggle/input'):\n"," for filename in filenames:\n"," print(os.path.join(dirname, filename))\n","\n","# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n","# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session"]}],"metadata":{"kaggle":{"accelerator":"none","dataSources":[],"isGpuEnabled":false,"isInternetEnabled":true,"language":"python","sourceType":"notebook"},"kernelspec":{"display_name":"Python 3","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.10.12"},"papermill":{"default_parameters":{},"duration":5.044334,"end_time":"2025-02-03T00:40:08.814458","environment_variables":{},"exception":null,"input_path":"__notebook__.ipynb","output_path":"__notebook__.ipynb","parameters":{},"start_time":"2025-02-03T00:40:03.770124","version":"2.6.0"}},"nbformat":4,"nbformat_minor":5}
--------------------------------------------------------------------------------
/supertrend_visualizer_parquet.py:
--------------------------------------------------------------------------------
1 | #Importation
2 | import ccxt,schedule,warnings,time,ast
3 | warnings.filterwarnings('ignore')
4 | import matplotlib.pyplot as plt
5 | from dateutil.tz import tzlocal
6 | from datetime import datetime
7 | import pyarrow.parquet as pq
8 | import seaborn as sns
9 |
10 | from PIL import Image
11 | import pandas as pd
12 | import numpy as np
13 |
14 | volatility=float(input("Volatility rate (example: 0.55555 for short-term volatility, 3 for long-term volatility.): "))
15 |
16 | #Supertrend
17 | def tr(data):
18 | data['previous_close']=data['close'].shift(1)
19 | data['high-low']=abs(data['high']-data['low'])
20 | data['high-pc']=abs(data['high']-data['previous_close'])
21 | data['low-pc']=abs(data['low']-data['previous_close'])
22 | tr=data[['high-low','high-pc','low-pc']].max(axis=1)
23 | return tr
24 | def atr(data, period):
25 | data['tr']=tr(data)
26 | atr=data['tr'].rolling(period).mean()
27 | return atr
28 | def supertrend(df,period=7,atr_multiplier=volatility):
29 | hl2=(df['high']+df['low'])/2
30 | df['atr']=atr(df, period)
31 | df['upperband']=hl2+(atr_multiplier*df['atr'])
32 | df['lowerband']=hl2-(atr_multiplier*df['atr'])
33 | df['in_uptrend']=True
34 | for current in range(1,len(df.index)):
35 | previous=current-1
36 | if df['close'][current]>df['upperband'][previous]:
37 | df['in_uptrend'][current]=True
38 | elif df['close'][current]df['upperband'][previous]:
45 | df['upperband'][current]=df['upperband'][previous]
46 | return df
47 |
48 | #Set user variables
49 | ticker=input("Insert the prefix of your ticker of choice: (example: LTC-USDT) ")
50 |
51 | #Read in historical data.
52 | df = pq.read_table(f'{ticker}.parquet').to_pandas().reset_index(drop=False)
53 | df = df.set_index('open_time')['close'].resample('1m').ohlc().reset_index(drop=False)
54 | #Or use the one below:
55 | #df=df[['timestamp','open','high','low','close']].head(5000)
56 | #df = df.sort_values('timestamp',ascending=True)
57 |
58 | #Apply supertrend formula
59 | supertrend_data= supertrend(df)
60 |
61 | #Set plot() params
62 | fig, ax = plt.subplots(figsize=(20, 8))
63 |
64 | #Signals 1.1
65 | xcoords_sell = supertrend_data[supertrend_data.in_uptrend == False].index
66 | xcoords_buy = supertrend_data[supertrend_data.in_uptrend == True].index
67 |
68 | #Signals 1.2
69 | for xc in xcoords_sell:
70 | plt.axvline(x=xc,c='r')
71 | for xc in xcoords_buy:
72 | plt.axvline(x=xc,c='g')
73 |
74 | #Plot close price
75 | ax.plot(supertrend_data.close, color = 'black', label = 'Line 1')
76 |
77 | #Plot bollinger bands
78 | ax.plot(supertrend_data.upperband, color = 'lime', label = 'upperband')
79 | ax.plot(supertrend_data.lowerband, color = 'pink', label = 'lowerband')
80 |
81 | #PLot outputs
82 | ax.legend(loc = 'upper left')
83 | plt.savefig(f'supertrend_visual_{ticker}_{volatility}.jpg')
84 | plt.show()
85 |
86 | #Open .jpg
87 | Image.open(f"supertrend_visual_{ticker}_{volatility}.jpg")
--------------------------------------------------------------------------------
/un-oracle-nigmatique.ipynb:
--------------------------------------------------------------------------------
1 | {"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[],"dockerImageVersionId":30822,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"source":" ","metadata":{},"cell_type":"markdown"},{"cell_type":"markdown","source":"# Un Oracle Énigmatique\n## A Debatably Profitable Autonomous Tradable Robotical Solvant, I mean Solution..,m\n\nThe code above integrates a Kalman Filter-based trend estimation to generate autonomous tradinğ signals for any åsset, including çryptocurrencies.\n\n# Welcome to our Universe\n## [@donutz.ai](www.donutz.ai/#)","metadata":{}},{"cell_type":"code","source":"from IPython.display import clear_output\n!pip install pykalman\n!pip install yfinance\nclear_output()","metadata":{"trusted":true,"_kg_hide-input":true,"execution":{"iopub.status.busy":"2025-01-04T07:51:42.548059Z","iopub.execute_input":"2025-01-04T07:51:42.54846Z","iopub.status.idle":"2025-01-04T07:51:50.703251Z","shell.execute_reply.started":"2025-01-04T07:51:42.548426Z","shell.execute_reply":"2025-01-04T07:51:50.701727Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport yfinance as yf\nfrom pykalman import KalmanFilter\nimport matplotlib.pyplot as plt\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n for filename in filenames:\n print(os.path.join(dirname, filename))\n\n# Function to fetch historical data\ndef fetch_data(ticker, start_date, end_date):\n print(\"Summoning the market's whispers...\")\n data = yf.download(ticker, start=start_date, end=end_date)\n data = pd.read_csv('https://www.cryptodatadownload.com/cdd/Binance_SHIBUSDT_1h.csv',header=1)\n data = data.tail(300)\n data['Return'] = data['Close'].pct_change()\n return data\n\n# Kalman Filter for trend estimation\ndef kalman_filter(prices):\n print(\"Unraveling the veils of uncertainty...\")\n kf = KalmanFilter(transition_matrices=[1], observation_matrices=[1],\n initial_state_mean=prices[0], n_dim_obs=1)\n state_means, _ = kf.filter(prices)\n return state_means\n\n# Trading signals based on Kalman Filter trend\ndef generate_signals(data):\n print(\"Deciphering cryptic signals...\")\n trend = kalman_filter(data['Close'].values)\n data['Trend'] = trend\n data['Signal'] = 0\n data.loc[data['Close'] > data['Trend'], 'Signal'] = 1 # Buy\n data.loc[data['Close'] < data['Trend'], 'Signal'] = -1 # Sell\n return data\n\n# Backtest the strategy\ndef backtest(data, initial_capital):\n print(\"Traversing the labyrinth of profits...\")\n data['Portfolio'] = initial_capital\n for i in range(1, len(data)):\n data.loc[data.index[i], 'Portfolio'] = (\n data['Portfolio'].iloc[i - 1] * (1 + data['Return'].iloc[i])\n if data['Signal'].iloc[i - 1] == 1 else data['Portfolio'].iloc[i - 1]\n )\n return data\n\n# Visualization\ndef plot_results(data, ticker):\n print(\"Revealing the hidden patterns...\")\n plt.figure(figsize=(24, 7))\n plt.plot(data['Close'], label='Price', alpha=0.666)\n plt.plot(data['Trend'], label='Kalman Trend', linestyle='--')\n plt.scatter(data.index, data['Close'][data['Signal'] == 1], label='Buy Signal', marker='^', color='green')\n plt.scatter(data.index, data['Close'][data['Signal'] == -1], label='Sell Signal', marker='v', color='red')\n plt.title(f\"{ticker} - Autonomous Trading Signals\")\n plt.legend()\n plt.show()\n\n# Main function\ndef main():\n ticker = \"SHIB-USD\" # Choose your asset\n start_date = \"2024-06-01\"\n end_date = \"2025-01-01\"\n initial_capital = 10000\n\n print(\"Awakening the algorithmic sage...\")\n data = fetch_data(ticker, start_date, end_date)\n data = generate_signals(data)\n data = backtest(data, initial_capital)\n\n print(f\"Final Portfolio Value: ${data['Portfolio'].iloc[-1]:.2f}\")\n plot_results(data, ticker)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-04T08:01:37.606385Z","iopub.execute_input":"2025-01-04T08:01:37.606746Z","iopub.status.idle":"2025-01-04T08:01:37.620177Z","shell.execute_reply.started":"2025-01-04T08:01:37.606717Z","shell.execute_reply":"2025-01-04T08:01:37.618707Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import warnings\nwarnings.filterwarnings(\"ignore\")\n\nmain()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-04T08:01:39.207732Z","iopub.execute_input":"2025-01-04T08:01:39.208262Z","iopub.status.idle":"2025-01-04T08:01:41.946349Z","shell.execute_reply.started":"2025-01-04T08:01:39.208207Z","shell.execute_reply":"2025-01-04T08:01:41.944645Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# en fin, din-din, ma tin mints, & cools goons balloons ain't for fools init, gov'nah!","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}
--------------------------------------------------------------------------------
|