VishvaAlgo V 2.0, a Live Cryptocurrency Trading system Enhanced with Machine Learning (Neural Network) model for Live Trading
Introduction:
In the ever-evolving landscape of algorithmic trading, where milliseconds can make or break fortunes, the quest for the ultimate trading bot has reached new heights. Traditional bots often grapple with limitations, such as employing common leverage or fixed stop-loss and take-profit levels across multiple assets, or being confined to trading a single asset at a time, missing out on lucrative opportunities elsewhere in the market. Moreover, the complexity of algorithmic trading in the cryptocurrency sphere presents unique challenges and opportunities, characterized by unparalleled volatility and 24/7 trading cycles.
Enter a game-changer: a Python-powered trading bot designed to transcend these constraints and redefine the possibilities of automated trading. This innovative solution leverages cutting-edge technologies, including machine learning and neural networks, to empower traders with unprecedented flexibility, adaptability, and predictive accuracy. With a focus on customization, optimization, and real-time decision-making, this bot represents a paradigm shift in algorithmic trading, poised to revolutionize the way traders navigate the crypto markets.
Previously Developed Algorithm based on same concept for Neural Networks:
Using Neural Networks Models:
Bitcoin/BTC 4750%+ , Etherium/ETH 11,270%+ profit in 1023 days using Neural Networks, Algorithmic Trading Vs/+ Machine Learning Models Vs/+ Deep Learning Model Part — 4 (TCN, LSTM, Transformer with Ensemble Method) — Link
This above article covers ensemble method combining TCN and LSTM neural network models has demonstrated exceptional performance across various datasets, outperforming individual models and even surpassing buy and hold strategies. This underscores the effectiveness of ensemble learning in improving prediction accuracy and robustness.
Using Machine learning (Boosting) Models:
From 54% to a Staggering 4648%: Catapulting Cryptocurrency Trading with CatBoost Classifier, Machine Learning Model at Its Best — Link
This above article covers the ensemble method, particularly employing classifiers such as Random Forest, Gradient Boosting, and CatBoost, has demonstrated exceptional returns with a stop loss of 10% and take profit of 2.5%, yielding an impressive return of 4648% over 1022 days, while maintaining a high winning rate of 81.17%. CatBoost’s stellar performance within the ensemble can be attributed to its effective handling of categorical features, robustness to noise, and automatic management of missing values, suggesting its adaptability across various market conditions.
Key Features Of New Live Trading Bot with Neural Network Easy Integration:
Flexibility and Customization:
Unlike conventional bots, which impose uniform parameters across assets, our bot offers unparalleled flexibility. Users can tailor settings such as leverage, stop-loss, and take-profit levels on a per-asset basis, allowing for precise risk management and optimization of trading strategies.
Multi-Asset Trading:
By enabling simultaneous trading across multiple assets, our bot capitalizes on diverse market opportunities, maximizing profit potential and mitigating risk. Gone are the days of overlooking promising assets due to the limitations of single-asset bots.
Real-Time Decision-Making:
In the fast-paced world of cryptocurrency trading, timing is everything. Our bot employs advanced algorithms and real-time data analysis to identify optimal entry and exit points, enabling swift and decisive action in response to market fluctuations.
Futures Trading and Predictive Insights:
Embracing the dynamic nature of futures trading, our bot goes beyond mere execution to offer predictive insights, guiding users on when to go long, short, or remain neutral. By anticipating market movements with precision, our bot empowers traders to stay ahead of the curve and capitalize on emerging opportunities.
Machine Learning Integration:
Harnessing the power of machine learning, our bot transcends traditional trading strategies by adapting to evolving market conditions and uncovering hidden patterns within complex data sets. With minimal adjustments, users can effortlessly integrate classification models, which excel in real-time prediction scenarios, outperforming regression models reliant on continuous data.
import time
import ccxt
from keras.models import save_model, load_model
import numpy as np
import pandas as pd
import talib as ta
from sklearn.preprocessing import MinMaxScaler
import warnings
from threading import Thread, Event
import decimal
import joblib
# from pandas.core.computation import PerformanceWarning
# Suppress PerformanceWarning
warnings.filterwarnings("ignore")
# Load your pre-trained model, keras trained model will only take load_model from keras.models and not from joblib
model = load_model('./best_model_lstm_1tp_1sl_2p5SlTp_success.h5')
exchange = ccxt.binanceusdm(
{
'enableRateLimit': True, # required by the Manual
# Add any other authentication parameters if needed
}
)
# exchange
# NOTE: I used https://testnet.binancefuture.com/en/futures/BTCUSDT for testnet API (this has very bad liquidity issue for various assets and many other issues but can be used for purely testiug purpose)
# kraken testnet creds pubkey - K9dS2SK8JURMl9F30guUhOS/ao3HM+tfNqRMgJGed+JhDfpJhvsC/y privatekey - /J/0kQ3PPyPwsrPsKZYtLqOQNPLKZJattT6i15Bpg14/6ALokHHY/MBb1p6tYKyFgkKXIJIOMbBsRfL3aBZUvQ1
api_key = '8f7080f8821b58a53f5c49f0041413d8cbff7447e2a2afdcce1cca9c9154ea'
secret_key = '1e58391a46a7dbb098aa512871d497c0052a9174e163e69e3a6660ba8c38f'
exchange.apiKey = api_key
exchange.secret = secret_key
exchange.set_sandbox_mode(True)
###################################################################################
# if u want to go live, un commenb below 5 lines and comment 5 lines above and change to your own api_key and secret_key (below one ius a dummy and also make sure to give "futres" permission while creating your api in the exchange)
# api_key = 'NAvJMmGIZY89mukwKhacKohlYmmK9BPH2LlRz8qVehdvx8lIDBvikBza'
# secret_key = '7j2MoKxQEsGS01KuSQtNwWCj6dHc5UnArkGGm3kxAO63tHWZq0NyRgIaz'
# exchange.apiKey = api_key
# exchange.secret = secret_key
# exchange.set_sandbox_mode(False)
#######################################################################################
# exchange.set_sandbox_mode(True)
exchange.has
exchange.fetchBalance()["info"]["assets"]
exchange.options = {'defaultType': 'future', # or 'margin' or 'spot'
'timeDifference': 0, # Set an appropriate initial value for time difference
'adjustForTimeDifference': True,
'newOrderRespType': 'FULL',
'defaultTimeInForce': 'GTC'}
Running the Trading Bot with Few Lines of Code:
# NOTE:
# `symbol` - you can mention any` symbol` here, but the bot will fetch symbol based on volume filter we used , this will only help in initating the bot and will not take actual symbol mentioned here
# `amount` - mention a default amount/quantity (ccxt strangely accepts quantity instead of USDT , will try to see a work-around technique to enter with USDT per trade rather than quantity in future updates, as of now just mention 0.001)
# `initial_timeframe` - set 1m as default, it will help in starting the whole thread faster within 1-2 candel lengths (1-2 mintues), if you use higher timeframe, it will take minimum 2 candles length to start the bot, so fix to using 1m
# `actual_timeframe` - mention the actual timeframe that your prediction model ot trained for , here , our LSTM neural network model got trained with `15m` timeframe and so we mentioned that.
# `leverage` - set leverage based on risk your bot can take, our model got trained at 1x leverage and so I used low risk of 2x leverage or can use 1x for best results possible. Further in future updates, we will train bots on hgher leverages and use this feature more profound way
# `sandbox` - set to True if using testnet, (binance testnet sucks, it doesnt work well at all but for testing purpose we can use it). In future updates, we will see if we can use dry-run in more better ways without depending on WRONG liqudity availability in testnets like binance testnet. I want to understand dry-run concept from freqtrade and implement something similar for our bot too in future updates.
# `stoploss_percent` & `takeprofit_percent` - set your stoploss accordingly, the present model had 10% stoploss which is 0.1 and take profit set at 0.025 , which is around 2.5% , further in future, we will work on good risk-to-reward ratios.
# `number_of_assets_to_trade` - please set functional int number based on model which got trained and after testing on various assets through backtest, only then use higher number. Future updates will have defined set of assets defined by user
# `custom_assets_enabled` by default is set to False, but if we want to use our own custom assets, then, this needs to be enabled.
# `custom_assets` - this takes dictionary values of asset name and corresponding key, value pairs of tp,sl,leverage and other things, you can set values as needed or use process_json(file_path) function to automate the short list of best perfoming assets with unique sl, tp and leverages after hyper tuning them and saving them under custom-assets.txt file, which an be fetch and used as required.
# `usdt_per_trade` - mention USDT you want to trade each asset with.
trader =CCXTFuturesTrader(symbol="BTC/USDT:USDT", initial_timeframe='1m', amount=0.01,
exchange=exchange, actual_timeframe = '15m', leverage=2, sandbox=True, stoploss_percent = 0.025, takeprofit_percent = 0.025,
number_of_assets_to_trade = 5, custom_assets_enabled=True, custom_assets=custom_assets, usdt_per_trade=25)
trader.start_trading(start = None, hist_bars = 200)
Saving Data:
Saving data of multiple cryptocurrencies from TradingView to local system to do backtesting and hyper-optimization on the machine learning models
# !pip install --upgrade --no-cache-dir git+https://github.com/rongardF/tvdatafeed.git
import os
import json
import asyncio
from datetime import datetime, timedelta
import pandas as pd
from tvDatafeed import TvDatafeed, Interval
# Initialize TvDatafeed object
# username = 'YourTradingViewUsername'
# password = 'YourTradingViewPassword'
# tv = TvDatafeed(username, password)
tv = TvDatafeed()
# List of symbols
data = [
"BTCUSDT.P", "GMTUSDT.P", "ETHUSDT.P", "MTLUSDT.P", "NEARUSDT.P", "SOLUSDT.P", "OGNUSDT.P", "ZILUSDT.P", "APEUSDT.P", "XRPUSDT.P", "ADAUSDT.P", "AVAXUSDT.P", "KNCUSDT.P", "DOGEUSDT.P", "WAVESUSDT.P", "1000SHIBUSDT.P", "FTMUSDT.P", "BNBUSDT.P", "XMRUSDT.P", "DOTUSDT.P", "GALAUSDT.P", "MATICUSDT.P", "LRCUSDT.P", "RUNEUSDT.P", "AUDIOUSDT.P", "FILUSDT.P", "ETCUSDT.P", "EOSUSDT.P", "ZECUSDT.P", "AXSUSDT.P", "LTCUSDT.P", "SANDUSDT.P", "LINKUSDT.P", "SXPUSDT.P", "ATOMUSDT.P", "BCHUSDT.P", "PEOPLEUSDT.P", "MANAUSDT.P", "AAVEUSDT.P", "ALICEUSDT.P", "BNXUSDT.P", "KAVAUSDT.P", "CRVUSDT.P", "ONEUSDT.P", "VETUSDT.P", "THETAUSDT.P", "DYDXUSDT.P", "ICPUSDT.P", "ALGOUSDT.P", "SUSHIUSDT.P", "RENUSDT.P", "COMPUSDT.P", "XLMUSDT.P", "CHZUSDT.P", "TLMUSDT.P", "TRXUSDT.P", "XTZUSDT.P", "FTTUSDT.P", "IMXUSDT.P", "CELRUSDT.P", "WOOUSDT.P", "HNTUSDT.P", "EGLDUSDT.P", "ENJUSDT.P", "CELOUSDT.P", "BATUSDT.P", "KSMUSDT.P", "UNIUSDT.P", "ROSEUSDT.P", "BAKEUSDT.P", "RSRUSDT.P", "IOSTUSDT.P", "GRTUSDT.P", "DASHUSDT.P", "ALPHAUSDT.P", "FLOWUSDT.P", "OCEANUSDT.P", "DENTUSDT.P", "CHRUSDT.P", "OMGUSDT.P", "HOTUSDT.P", "LINAUSDT.P", "SRMUSDT.P", "COTIUSDT.P", "SKLUSDT.P", "NEOUSDT.P", "SNXUSDT.P", "ICXUSDT.P", "ARUSDT.P", "1INCHUSDT.P", "API3USDT.P", "ANKRUSDT.P", "DUSKUSDT.P", "REEFUSDT.P", "BALUSDT.P", "BANDUSDT.P", "ZRXUSDT.P", "C98USDT.P", "QTUMUSDT.P", "STORJUSDT.P", "IOTAUSDT.P", "ONTUSDT.P", "MASKUSDT.P", "GTCUSDT.P", "HBARUSDT.P", "MKRUSDT.P", "TOMOUSDT.P", "ENSUSDT.P", "ZENUSDT.P", "SFPUSDT.P", "CVCUSDT.P", "IOTXUSDT.P", "CTKUSDT.P", "FLMUSDT.P", "NKNUSDT.P", "YFIUSDT.P", "RLCUSDT.P", "BTSUSDT.P", "KLAYUSDT.P", "BELUSDT.P", "XEMUSDT.P", "ANTUSDT.P", "SCUSDT.P", "LITUSDT.P", "CTSIUSDT.P", "STMXUSDT.P", "UNFIUSDT.P", "RVNUSDT.P", "1000XECUSDT.P", "RAYUSDT.P", "BLZUSDT.P", "ATAUSDT.P", "ARPAUSDT.P", "DGBUSDT.P", "LPTUSDT.P", "TRBUSDT.P", "OPUSDT.P", "GALUSDT.P"
]
nest_asyncio.apply()
# Define data download function
async def download_data(symbol):
try:
data = tv.get_hist(symbol=symbol, exchange='BINANCE', interval=Interval.in_15_minute, n_bars=20000, extended_session=True)
if not data.empty:
# Convert Date objects to strings
# data['Date'] = data.index.date.astype(str)
# data['Time'] = data.index.time.astype(str)
data['date'] = data.index.astype(str) # Add a new column for timestamps
folder_name = "tradingview_crypto_assets_15m"
os.makedirs(folder_name, exist_ok=True)
# Replace "USDT.P" with "/USDT:USDT" in the file name
symbol_file_name = symbol.replace("USDT.P", "") + ".json"
file_name = os.path.join(folder_name, symbol_file_name)
# Convert DataFrame to dictionary
data_dict = data.to_dict(orient='records')
with open(file_name, "w") as file:
# Serialize dictionary to JSON
json.dump(data_dict, file)
print(f"Data for {symbol} downloaded and saved successfully.")
else:
print(f"No data available for {symbol}.")
except Exception as e:
print(f"Error occurred while downloading data for {symbol}: {e}")
# Define main function to run async download tasks
async def main():
tasks = [download_data(symbol) for symbol in data]
await asyncio.gather(*tasks)
# Run the main function
asyncio.run(main())
Backtesting Strategy with below function which has Specific Stop Loss, Take profit, leverage setup done:
# Define MyCandlesStrat_3 class
class MyCandlesStrat_3(Strategy):
sl_pct_l = best_params['BEST_STOP_LOSS_sl_pct_long']
tp_pct_l = best_params['BEST_TAKE_PROFIT_tp_pct_long']
limit_l = best_params['BEST_LIMIT_ORDER_limit_long']
sl_pct_s = best_params['BEST_STOP_LOSS_sl_pct_short']
tp_pct_s = best_params['BEST_TAKE_PROFIT_tp_pct_short']
limit_s = best_params['BEST_LIMIT_ORDER_limit_short']
margin_leverage = best_params['BEST_LEVERAGE_margin_leverage']
# sl_pct_l = 0.025
# tp_pct_l = 0.025
# limit_l = 0.024
# sl_pct_s = 0.025
# tp_pct_s = 0.025
# limit_s = 0.024
# margin_leverage = 2
def init(self):
super().init()
self.signal1 = self.I(SIGNAL_3, self.data)
def next(self):
super().next()
# if self.position:
if (self.signal1 == 1):
# sl_pct = 0.005 # 2% stop-loss
# tp_pct = 0.005 # 5% take-profit
sl_price = self.data.Close[-1] * (1 - (self.sl_pct_l * 0.001))
tp_price = self.data.Close[-1] * (1 + (self.tp_pct_l * 0.001))
limit_price = tp_price * 0.996
self.position.is_long
self.buy(sl=sl_price, limit=limit_price, tp=tp_price)
elif (self.signal1 == 2):
# sl_pct = 0.005 # 2% stop-loss
# tp_pct = 0.005 # 5% take-profit
sl_price = self.data.Close[-1] * (1 + (self.sl_pct_s * 0.001))
tp_price = self.data.Close[-1] * (1 - (self.tp_pct_s * 0.001))
limit_price = sl_price * 0.996
self.position.is_short
self.sell(sl=sl_price, limit=limit_price, tp=tp_price)
# Run backtest
bt_3 = Backtest(df_ens, MyCandlesStrat_3, cash=100000, commission=.001, margin= (1/MyCandlesStrat_3.margin_leverage), exclusive_orders=False)
stat_3 = bt_3.run()
print("backtest one done at 226 line - ", stat_3)
Optimizing The Strategy to Find Best Parameters for Trading:
# Optimization
def optimize_strategy():
# Optimization Params
optimizer = 'Sharpe Ratio'
stats = bt_3.optimize(
sl_pct_l = range(6,100, 2), # (5,10,15,20,25,30,40,50,75,100)
tp_pct_l = range(6,100, 2), # (0.005, 0.01, 0.015, 0.02, 0.025, 0.03, 0.04, 0.05, 0.075, 0.1)
# limit_l = (4,9,14,19,24,29,39,49,74,90),# (0.004, 0.009, 0.014, 0.019, 0.024, 0.029, 0.039, 0.049, 0.074, 0.09)
sl_pct_s = range(6,100, 2),
tp_pct_s = range(6,100, 2),
# limit_s = (4,9,14,19,24,29,39,49,74,90),
margin_leverage = range(1, 6),
constraint=lambda p: ( (p.sl_pct_l > (p.tp_pct_l + 4) ) and ((p.sl_pct_s) > (p.tp_pct_s + 4) )),
maximize = optimizer,
return_optimization=True,
method = 'skopt',
max_tries = 100 # 20% for 0.2 and 100% for 1.0, this applys when not using 'skopt' method, for 'skopt' number starts from 1 to 200 max epochs
)
# Extract the optimization results
best_params = {
'Optimizer': optimizer,
'OptimizerResult_Cross': stats[0][optimizer],
'BEST_STOP_LOSS_sl_pct_long': stats[1].x[0],
'BEST_TAKE_PROFIT_tp_pct_long': stats[1].x[1] ,
'BEST_LIMIT_ORDER_limit_long': stats[1].x[1] * 0.997,
'BEST_STOP_LOSS_sl_pct_short': stats[1].x[2] ,
'BEST_TAKE_PROFIT_tp_pct_short': stats[1].x[3] ,
'BEST_LIMIT_ORDER_limit_short': stats[1].x[3] * 0.997,
'BEST_LEVERAGE_margin_leverage': stats[1].x[4]
}
return best_params
Custom Assets list auto saved after running HyperOptimization on machine Learning lead backtesting.
My Sales Pitch for the Live Crypto Trading bot with Easy Neural Networks Integration: (A Machine Learning Live Trading Bot)
🚀🔥 Unlock Your Crypto Trading Potential with Our Revolutionary Bot! 🔥🚀
Calling all crypto enthusiasts, financial wizards, and machine learning mavens! 📈💰
Are you ready to elevate your trading game to new heights? Introducing our cutting-edge trading bot, meticulously crafted to cater to the needs of the modern trader. Say goodbye to manual guesswork and hello to the future of automated trading powered by Machine Learning and Neural Networks!
🔥 Latest Updates — March 25th, 2024: 🔥
✨ Custom Asset Integration: Now, tailor your trading experience with custom assets, complete with personalized settings for take profit, stop loss, and leverage. Trade with confidence, your way!
✨ Hyper-Tuned Asset Selection: Our bot does the heavy lifting for you, automatically identifying the best crypto assets for your ML/DL models through rigorous hyper-tuning and backtesting. Say hello to smarter trading decisions!
✨ Multi-Asset Trading: Trade multiple assets simultaneously with ease. Take full control of your portfolio and diversify like never before!
✨ USDT Value Trading: Introducing trading with specified USDT value for added flexibility and precision in your transactions.
✨ Enhanced Performance: With improved error handling, threading, multiprocessing, GPU activation, and CPU core utilization, experience lightning-fast performance and seamless execution.
✨ Neural Network Integration: Fine-tune your trading strategies with our Neural Network model, complete with preprocessing steps for optimal results.
✨ Data Access Simplified: Say goodbye to hassles! Access data from TradingView effortlessly, no login credentials required.
✨ Easy Setup: Follow our straightforward package installation instructions for a hassle-free setup process. Get started in minutes!
💡 Description: Our trading bot revolutionizes the way you trade cryptocurrencies. Train, test, backtest, and deploy ML/DL models effortlessly across various assets and time frames. Customize to your heart’s content and unleash its power for live or paper trading. Experience seamless execution, comprehensive functionality, and detailed trading reports across multiple exchanges.
🌟 Take the First Step Towards Trading Success: 🌟
Unlock the full potential of your trading journey with our innovative bot. Hyper-optimize your models, run extensive tests, and dive into the world of automated trading with confidence. Need assistance or have suggestions? We’re here for you every step of the way.
🚀 Don’t miss out on this opportunity to supercharge your trading strategies and embark on a journey to financial freedom! 🚀
👉 Click here to seize the opportunity:
Here’s to your success in the thrilling world of crypto trading!
Conclusion:
In conclusion, the emergence of our Python-powered trading bot represents a quantum leap forward in the realm of algorithmic trading. By addressing the limitations inherent in existing bots and leveraging the unparalleled capabilities of machine learning and neural networks, our bot offers a trans-formative solution for traders seeking to navigate the complexities of the cryptocurrency markets with confidence and precision. With its unparalleled flexibility, multi-asset trading capabilities, real-time decision-making prowess, and integration of cutting-edge technologies, our bot stands poised to revolutionize the way traders approach automated trading. Embrace the future of trading with our bot and unlock a world of possibilities in the ever-expanding realm of cryptocurrency trading.
Bot Link — https://www.patreon.com/pppicasso/shop/vishvaalgo-v2-0-live-crypto-trading-156496
Warm Regards,
Puranam Pradeep Picasso
Linkedin — https://www.linkedin.com/in/puranampradeeppicasso/
Patreon — https://patreon.com/pppicasso
Facebook — https://www.facebook.com/puranam.p.picasso/
Twitter — https://twitter.com/picasso_999