Liquidation data can be highly informative

I Decoded The Liquidity & Manipulation Algorithm In Day Trading
DGM Payment - SOLUSDT SMC 30m

Liquidation data can be highly informative when combined with metrics like volume, open interest, or funding rate. These three indicators help provide a clearer picture of market behavior and trader sentiment. Here’s how each works with liquidation data:

1. Volume and Liquidation:

  • Volume represents the total number of contracts or shares traded during a specific period.
  • Liquidations combined with high volume can signal a significant market move, as many traders are being forced out of their positions. For example, a spike in long liquidations combined with high selling volume often indicates a strong downward price movement, and vice versa for short liquidations.
  • Key Insight: When liquidations happen in high-volume conditions, it suggests strong conviction in the direction of the move.

2. Open Interest and Liquidation:

  • Open Interest (OI) represents the total number of outstanding contracts (positions) in a market.
  • Decreases in OI after large liquidations suggest positions are being closed, potentially marking the end of a strong move (e.g., a final shakeout).
  • Increases in OI with liquidations may indicate that new positions are being opened, often by more aggressive participants looking to capitalize on the forced liquidations of others.
  • Key Insight: A combination of high liquidations and falling OI could signal the exhaustion of a trend.

3. Funding Rate and Liquidation:

  • Funding Rate incentivizes traders to take long or short positions based on market imbalance.
  • Liquidations in the context of extreme funding rates are often a precursor to reversals. For example, if funding rates are extremely positive (indicating longs are paying shorts), and then a large number of long liquidations occur, it might signal that overly leveraged longs are being forced to exit, potentially triggering a downward move.
  • Key Insight: Funding rates help identify the positioning of the majority of traders. If liquidations occur with extremely skewed funding rates, it often means the market was over-leveraged in one direction, which could result in a price correction.

Summary of How They Work Together:

  • Volume + Liquidations: High liquidations with high volume = strong price moves with conviction.
  • Open Interest + Liquidations: High liquidations with falling OI = potential trend exhaustion; with rising OI = fresh participants entering.
  • Funding Rate + Liquidations: High liquidations with extreme funding rates = potential market reversal due to overly leveraged positions being wiped out.

Each of these indicators adds valuable context to liquidation data, and using them together can help you make more informed trading decisions.

Sign Up Bybit

How to use Funding Rate in Algo Trading?

How to use Funding Rate in Algo Trading?
Alt Coin 8 Hours Funding Rate Chart

1. Mean Reversion Strategy

  • How it works: The funding rate can indicate market sentiment and extreme positions. If funding rates are very high or low, it suggests that one side of the market (long or short) is overleveraged. A mean reversion strategy involves entering positions expecting the funding rate to revert to more normal levels.
  • Goal: Bet against extreme funding rates, profiting from their eventual reversion as market sentiment stabilizes.

2. Market Sentiment Analysis

  • How it works: Funding rates can be used as a proxy for sentiment. High positive funding rates indicate bullish sentiment, while negative rates indicate bearish sentiment. Algorithms can use this information to adjust their trading strategies in line with prevailing market trends or take contrarian positions.
  • Goal: Capitalize on market momentum or sentiment shifts based on funding rate extremes.

3. Directional Trading Strategy

Goal: Align trades with the prevailing market direction as indicated by the funding rate or use it to enter contrarian positions when rates are extreme.

How it works: If the funding rate is positive and increasing, it suggests that long positions are dominating the market, while a negative and decreasing rate suggests shorts are prevailing. This information can be used in trend-following strategies.

import pandas as pd
import numpy as np
import random

Simulate funding rate data (Replace this with actual API data)

def simulate_funding_rate_data(n=100):
dates = pd.date_range(end=pd.Timestamp.now(), periods=n, freq=’H’)
funding_rates = np.random.normal(0, 0.01, n) # Random funding rates between -1% to +1%
return pd.DataFrame({‘date’: dates, ‘funding_rate’: funding_rates})

Generate funding rate data

df = simulate_funding_rate_data()

Define trading strategies

class FundingRateStrategy:

def __init__(self, funding_rate_data, upper_threshold=0.005, lower_threshold=-0.005):
    self.funding_rate_data = funding_rate_data
    self.upper_threshold = upper_threshold
    self.lower_threshold = lower_threshold

# 1. Mean Reversion Strategy
def mean_reversion_strategy(self):
    """
    Mean reversion based on extreme funding rates. Enter contrarian positions when funding rates
    are too high (short) or too low (long).
    """
    signals = []
    for index, row in self.funding_rate_data.iterrows():
        if row['funding_rate'] > self.upper_threshold:
            signals.append('Sell')  # High funding rate -> Overleveraged long positions -> Short
        elif row['funding_rate'] < self.lower_threshold:
            signals.append('Buy')   # Low funding rate -> Overleveraged short positions -> Long
        else:
            signals.append('Hold')  # No trade signal
    self.funding_rate_data['mean_reversion_signal'] = signals

# 2. Market Sentiment Analysis
def market_sentiment_analysis(self):
    """
    Market sentiment analysis based on funding rate. Positive funding rates indicate bullish sentiment,
    negative funding rates indicate bearish sentiment.
    """
    sentiment = []
    for index, row in self.funding_rate_data.iterrows():
        if row['funding_rate'] > 0:
            sentiment.append('Bullish')
        else:
            sentiment.append('Bearish')
    self.funding_rate_data['market_sentiment'] = sentiment

# 3. Directional Trading Strategy
def directional_trading_strategy(self):
    """
    Trade based on the direction of the funding rate. If the funding rate is increasing, it indicates a 
    bullish trend, otherwise, a bearish trend.
    """
    signals = []
    previous_rate = None
    for index, row in self.funding_rate_data.iterrows():
        if previous_rate is None:
            signals.append('Hold')
        elif row['funding_rate'] > previous_rate:
            signals.append('Buy')   # Funding rate is increasing, suggesting bullish trend
        elif row['funding_rate'] < previous_rate:
            signals.append('Sell')  # Funding rate is decreasing, suggesting bearish trend
        else:
            signals.append('Hold')
        previous_rate = row['funding_rate']
    self.funding_rate_data['directional_signal'] = signals

def run_strategies(self):
    """
    Run all strategies and generate trade signals.
    """
    self.mean_reversion_strategy()
    self.market_sentiment_analysis()
    self.directional_trading_strategy()
    return self.funding_rate_data

Instantiate the strategy class and run the strategies

strategy = FundingRateStrategy(funding_rate_data=df)
results = strategy.run_strategies()

Show the result with trade signals

print(results[[‘date’, ‘funding_rate’, ‘mean_reversion_signal’, ‘market_sentiment’, ‘directional_signal’]])

Funding Rate Trading Strategy. How to use Funding Rates?

Premium Index and Open Interest / Market Cap Ratio




The relationship between the Bybit Premium Index and the Open Interest/Market Cap (OI/MC) ratio is nuanced and can provide deeper insights into market sentiment and potential trading strategies. Here’s how they interrelate:

1. Bybit Premium Index:

  • Indicates the difference between the perpetual futures contract price and the spot price. A positive premium suggests futures are trading above the spot price, indicating bullish sentiment, while a negative premium suggests the opposite.

2. Open Interest/Market Cap Ratio (OI/MC Ratio):

  • This ratio compares the total number of outstanding futures contracts (Open Interest) to the market capitalization of the underlying asset. A higher ratio indicates more leveraged positions relative to the asset’s total market value, while a lower ratio suggests fewer leveraged positions.

Relationship Between Bybit Premium Index and OI/MC Ratio:

  1. High OI/MC Ratio with High Premium Index:
    • Interpretation: This scenario often indicates strong bullish sentiment and aggressive speculative activity. Traders are highly leveraged on the expectation that the asset’s price will rise.
    • Implications:
      • Potential Overheating: If the ratio is excessively high, it might indicate that the market is overheated, with too many leveraged positions. This could lead to increased volatility and a higher risk of liquidations if the market moves against these positions.
      • Bullish Signal: In a sustained bull market, this combination could signal continued price increases as traders are confident in their positions.
  2. High OI/MC Ratio with Low or Negative Premium Index:
    • Interpretation: This could indicate that despite the high number of leveraged positions, traders are expecting a price decline, or they are hedging against potential downturns.
    • Implications:
      • Bearish Signal: This might suggest bearish sentiment or fear in the market. Traders might be shorting the asset or hedging their long positions, anticipating a drop in price.
      • Market Caution: A high OI/MC ratio with a low premium might also signal that the market is cautious, with traders expecting volatility or a reversal.
  3. Low OI/MC Ratio with High Premium Index:
    • Interpretation: This could indicate that while there’s bullish sentiment (evidenced by the high premium), the overall market is not heavily leveraged. Traders might be cautious or simply not fully committed to leveraged positions.
    • Implications:
      • Cautious Optimism: The market might be bullish but is not yet in a speculative frenzy. This could suggest a more sustainable upward trend, with the potential for further increases in Open Interest as confidence grows.
  4. Low OI/MC Ratio with Low or Negative Premium Index:
    • Interpretation: This scenario suggests a lack of interest or confidence in the market, with fewer leveraged positions and little to no bullish sentiment.
    • Implications:
      • Bearish or Neutral Sentiment: The market might be bearish, or traders could be waiting for clearer signals before taking on leveraged positions.
      • Potential for Reversal: A low OI/MC ratio with a low premium might indicate that the market is oversold and could be primed for a reversal if new interest or catalysts emerge.

Practical Considerations:

  • Market Conditions: The relationship between these metrics can vary depending on broader market conditions. For example, in a bull market, a high OI/MC ratio with a high premium might be more sustainable, while in a bear market, it could lead to quicker corrections.
  • Leverage Risks: A high OI/MC ratio indicates that a significant portion of the market is leveraged, which can increase the risk of large price swings due to liquidations.

Conclusion:

The Bybit Premium Index and the OI/MC ratio together can provide insights into market sentiment, leverage, and potential price movements. Analyzing these metrics in conjunction can help traders gauge the market’s risk level and anticipate possible shifts in trend or volatility.

Tips:

Despite of the crypto dump recently on all the alt coins after SEC announcement to sue Binance and Coinbase. Guess what? My Ai Trading Strategies are making shit ton of USDT from the crazy markets. Well there is a secret and cannot tell you unless…Anyway, I have given you the formula to copy and it is up to you to trade manually with stress and sleepless nights or ride on the trend of Ai trading today ⬇️⬇️⬇️


AI Sleeping Income With DGM System

The SECRET is to marry between Ai trading strategies and an income generated exchange platform

  • Ai trading strategies

  • An income generated exchange platform

How It Works?


Implied Volatility (IV) Versus Open Interest / Market Cap Ratio

Key Differences:

  1. Implied Volatility (IV):
  • What It Is: IV is a measure derived from the price of an option, indicating the market’s expectations of the underlying asset’s future volatility.
  • Interpretation: Higher IV suggests that the market expects more volatility (larger price swings) in the underlying asset, while lower IV indicates expectations of less volatility.
  • Use in Trading: IV is used to price options and can give clues about the level of uncertainty or risk perceived by the market.

import scipy.optimize as opt
from math import log, sqrt, exp
from scipy.stats import norm

Black-Scholes Model to calculate the option price

def black_scholes_call(S, K, T, r, sigma):
d1 = (log(S / K) + (r + 0.5 * sigma ** 2) * T) / (sigma * sqrt(T))
d2 = d1 – sigma * sqrt(T)
call_price = S * norm.cdf(d1) – K * exp(-r * T) * norm.cdf(d2)
return call_price

def black_scholes_put(S, K, T, r, sigma):
d1 = (log(S / K) + (r + 0.5 * sigma ** 2) * T) / (sigma * sqrt(T))
d2 = d1 – sigma * sqrt(T)
put_price = K * exp(-r * T) * norm.cdf(-d2) – S * norm.cdf(-d1)
return put_price

Function to calculate implied volatility

def implied_volatility(option_price, S, K, T, r, option_type=’call’):
def objective_function(sigma):
if option_type == ‘call’:
return black_scholes_call(S, K, T, r, sigma) – option_price
elif option_type == ‘put’:
return black_scholes_put(S, K, T, r, sigma) – option_price

# Debug: Print the value of the objective function at the bounds
print(f"Objective function at sigma=0.0001: {objective_function(0.0001)}")
print(f"Objective function at sigma=5.0: {objective_function(5.0)}")

# Check if the function changes signs
if objective_function(0.0001) * objective_function(5.0) > 0:
    raise ValueError("The objective function does not change signs over the interval.")

# Using a numerical method to find the root, i.e., the implied volatility
iv = opt.brentq(objective_function, 0.0001, 5.0)  # Bound between 0.01% and 500%
return iv
Example data

S_eth = 1850 # Current price of ETH in USD
S_sol = 25 # Current price of SOL in USD
S_btc = 30000 # Current price of BTC in USD

K = 2000 # Strike price of the option
T = 30 / 365 # Time to expiration in years (e.g., 30 days)
r = 0.05 # Risk-free interest rate (5% annualized)
option_price_eth = 100 # Current price of the ETH option in USD
option_price_sol = 5 # Current price of the SOL option in USD
option_price_btc = 1200 # Current price of the BTC option in USD

Calculate Implied Volatility

try:
iv_eth = implied_volatility(option_price_eth, S_eth, K, T, r, option_type=’call’)
print(f”ETH Implied Volatility: {iv_eth:.2%}”)
except ValueError as e:
print(f”Error calculating IV for ETH: {e}”)

try:
iv_sol = implied_volatility(option_price_sol, S_sol, K, T, r, option_type=’call’)
print(f”SOL Implied Volatility: {iv_sol:.2%}”)
except ValueError as e:
print(f”Error calculating IV for SOL: {e}”)

try:
iv_btc = implied_volatility(option_price_btc, S_btc, K, T, r, option_type=’call’)
print(f”BTC Implied Volatility: {iv_btc:.2%}”)
except ValueError as e:
print(f”Error calculating IV for BTC: {e}”)

  1. Open Interest / Market Cap Ratio:

What It Is: This ratio is calculated by dividing the open interest in derivatives (futures or options) by the market cap of the underlying asset.

Interpretation: It reflects the level of speculative interest in the asset relative to its total market value. A higher ratio may indicate more speculative trading relative to the asset’s size, while a lower ratio might indicate less speculative activity.

Use in Trading: This ratio is used to assess the scale of derivatives trading in relation to the size of the asset, which can offer insights into market sentiment and potential liquidity risks.

import requests

Function to get market cap from CoinGecko API

def get_market_cap(coin_id):
url = f’https://api.coingecko.com/api/v3/coins/{coin_id}’
response = requests.get(url)
data = response.json()
market_cap = data[‘market_data’][‘market_cap’][‘usd’] # Market cap in USD
return market_cap

Function to get open interest from Binance Futures API

def get_open_interest(symbol):
url = ‘https://fapi.binance.com/fapi/v1/openInterest’
params = {‘symbol’: symbol}
response = requests.get(url, params=params)
data = response.json()
open_interest = float(data[‘openInterest’]) # Open interest in the base currency
return open_interest

Function to calculate the Open Interest / Market Cap Ratio

def calculate_oi_market_cap_ratio(coin_id, symbol):
market_cap = get_market_cap(coin_id)
open_interest = get_open_interest(symbol)
ratio = open_interest / market_cap
return ratio

Calculate and print the ratio for ETH

eth_ratio = calculate_oi_market_cap_ratio(‘ethereum’, ‘ETHUSDT’)
print(f”ETH Open Interest / Market Cap Ratio: {eth_ratio:.10f}”)

Calculate and print the ratio for SOL

sol_ratio = calculate_oi_market_cap_ratio(‘solana’, ‘SOLUSDT’)
print(f”SOL Open Interest / Market Cap Ratio: {sol_ratio:.10f}”)

Calculate and print the ratio for BTC

btc_ratio = calculate_oi_market_cap_ratio(‘bitcoin’, ‘BTCUSDT’)
print(f”BTC Open Interest / Market Cap Ratio: {btc_ratio:.10f}”)

Summary:

  • IV is specifically related to the expected future volatility of an asset, as perceived by the market through the pricing of options.
  • Open Interest / Market Cap Ratio gives a sense of the speculative interest relative to the size of the asset but does not directly measure volatility.

While both are useful in understanding market dynamics, they serve different purposes and are derived from different data points.




Tips:

Despite of the crypto dump recently on all the alt coins after SEC announcement to sue Binance and Coinbase. Guess what? My Ai Trading Strategies are making shit ton of USDT from the crazy markets. Well there is a secret and cannot tell you unless…Anyway, I have given you the formula to copy and it is up to you to trade manually with stress and sleepless nights or ride on the trend of Ai trading today ⬇️⬇️⬇️


AI Sleeping Income With DGM System

The SECRET is to marry between Ai trading strategies and an income generated exchange platform

  • Ai trading strategies

  • An income generated exchange platform

How It Works?


China Versus Malaysia In Kick Boxing Games

In a recent kickboxing event between China and Malaysia, China’s team demonstrated a strong performance, winning several key matches. Malaysia also put up a notable fight, securing victories in some categories. Both teams showcased high levels of skill and competitiveness.

Register Now

 

 

The Hidden Gems
利用人工智能和加密货币实现国界无形化的概念非常有趣

@DailyGameMoments (DGM) AI Services in AWS

Solana (SOL) Performance has a better result.

To enhance your trading strategy by using only DGM AI services and eliminating manual trading, you can follow these steps:

1. Define Your Trading Strategy

Create a well-defined trading strategy that outlines your entry and exit points, risk management rules, and the types of assets you wish to trade (stocks, futures, forex, crypto).

2. Set Up a DGM AI Account

Sign up for DGM AI services if you haven’t already. Familiarize yourself with the platform’s capabilities, available APIs, and any documentation provided.

3. Integrate DGM AI with Your Trading Platform

Use the DGM AI API to integrate their services with your trading platform. This may involve:

  • Fetching market data
  • Receiving trading signals
  • Executing trades automatically

4. Automate Trade Execution

Develop a script or use a trading bot that will automatically execute trades based on the signals provided by DGM AI. Here’s an example in Python using a hypothetical API structure:

Python Code:

import requests

API_KEY = ‘your_dgm_api_key’
BASE_URL = ‘https://api.dgm.ai’

def get_trading_signal(asset):
response = requests.get(f'{BASE_URL}/signals/{asset}’, headers={‘Authorization’: f’Bearer {API_KEY}’})
return response.json()

def execute_trade(signal):
trade_data = {
‘symbol’: signal[‘symbol’],
‘side’: signal[‘side’],
‘quantity’: signal[‘quantity’],
‘price’: signal[‘price’]
}
response = requests.post(f'{BASE_URL}/execute’, json=trade_data, headers={‘Authorization’: f’Bearer {API_KEY}’})
return response.json()

Example usage
signal = get_trading_signal(‘BTCUSD’)
if signal[‘confidence’] > 0.8:
trade_result = execute_trade(signal)
print(trade_result)

5. Backtest and Optimize

Before going live, backtest your strategy using historical data to ensure its profitability. Optimize your parameters based on the backtest results.

6. Monitor and Adjust

Regularly monitor the performance of your automated trading system. Make adjustments as needed to adapt to changing market conditions.

7. Ensure Security

Ensure that your API keys and sensitive information are stored securely. Implement necessary security measures to protect your trading system from unauthorized access.

8. Stay Updated

Stay updated with any changes or improvements in the DGM AI services. Regularly check for updates in the API and new features that might enhance your trading strategy.

By following these steps, you can transition to fully automated trading using DGM AI services, thereby eliminating the need for manual trading.




Tips:

Despite of the crypto dump recently on all the alt coins after SEC announcement to sue Binance and Coinbase. Guess what? My Ai Trading Strategies are making shit ton of USDT from the crazy markets. Well there is a secret and cannot tell you unless…Anyway, I have given you the formula to copy and it is up to you to trade manually with stress and sleepless nights or ride on the trend of Ai trading today ⬇️⬇️⬇️


AI Sleeping Income With DGM System

The SECRET is to marry between Ai trading strategies and an income generated exchange platform

  • Ai trading strategies

  • An income generated exchange platform

How It Works?


DGM AI Testing Performance

Solana (SOL) Performance has a better result.

Recent Short and Long Position Used by DGM AI

Long position with 75x leverage




Tips:

Despite of the crypto dump recently on all the alt coins after SEC announcement to sue Binance and Coinbase. Guess what? My Ai Trading Strategies are making shit ton of USDT from the crazy markets. Well there is a secret and cannot tell you unless…Anyway, I have given you the formula to copy and it is up to you to trade manually with stress and sleepless nights or ride on the trend of Ai trading today ⬇️⬇️⬇️


AI Sleeping Income With DGM System

The SECRET is to marry between Ai trading strategies and an income generated exchange platform

  • Ai trading strategies

  • An income generated exchange platform

How It Works?


Mean Reversion Strategy Python codes

  • This is not a money game.
  • This is not a manual trading system,
  • This is not a trading system with charts and indicators.
  • This is not a paid solution, this is DGM sleeping solution.
  • This is not an investment program and it is a trading Ai strategy.
  • This is not coins staking nor yield farming or to provide liquidation.
  • This is not TradingView pine scripts trading or webhook complicated settings.
  • This is not financial advise and Do Your Own Research (DYOR). You need only 3 steps!
  • This is not limited to one crypto exchange that you can use. More than one that you can choose.
  • This is not a solution without DGM guidance. I will provide a guidance which cryptocurrencies to trade.
  • This is not MT4/MT5 or EA and has nothing to do with VPS or setup a mini-PC to automate your trades.

Step 1: Setup an Ai Trading System in AWS.

The basic cost for AWS hosting to run Python codes and WordPress hosting is just $5 USD per month only.

Step 2: Setup A Trading Platform by adjusting the setting for both Mean Reversion & Trending Strategies

Mean Reversion Trading Strategy

Step 3: Monitor and Observe the AI Performance Forever

How can you do that?

  1. Create an application programming interface (API) with any exchange platforms (Cryptos or Options).
  2. Paste the API secret keys into the Python codes.
  3. Your job is done! You will make the passive income daily!

Do you want to setup your Casino and start earning interest rates? Follow me to read on 

Sharpe vs Sortino Ratio | Differences Explained

@DailyGameMoments

Test EMA Strategy 1:

Test SMA Strategy 2:

DGM Class Start Date and Time now is 2024-05-19 14:18:50.497258
START: 30m SOLUSDT OHLC-data from 2020-11-11 00:00:00 until 2024-05-19
DGM Class Start Date and Time now is 2024-05-19 14:22:57.747713
START: 30m SOLUSDT OHLC-data from 2020-11-11 00:00:00 until 2024-05-19
Open Time Open High Low Close
0 2020-11-10 16:00:00 2.1840 2.2528 2.1839 2.2484
1 2020-11-10 16:30:00 2.2484 2.2485 2.2304 2.2409
2 2020-11-10 17:00:00 2.2395 2.2995 2.2255 2.2790
3 2020-11-10 17:30:00 2.2790 2.2869 2.2438 2.2554
4 2020-11-10 18:00:00 2.2518 2.2554 2.2111 2.2111
.. … … … … …
659 2024-05-19 04:00:00 174.3200 174.4100 173.3100 173.5900
660 2024-05-19 04:30:00 173.5900 174.5000 173.3500 174.5000
661 2024-05-19 05:00:00 174.5000 175.5000 174.3600 174.8500
662 2024-05-19 05:30:00 174.8600 174.9400 173.8600 174.0700
663 2024-05-19 06:00:00 174.0700 174.3400 173.9200 174.1400

[61664 rows x 5 columns]
END: v3/klines 30m SOLUSDT DB Processed.

START DB Processing: >>> Data from GetDataRequested table.
Mean Price: 62.08541965814739
Standard Deviation: 58.721715230338866
v3/klines Upper Percentage Threshold: 179.52885011882512
v3/klines Lower Percentage Threshold: -55.358010802530345
Open Time High Low Close
0 2020-11-10 16:00:00 2.2528 2.1839 2.2484
1 2020-11-10 16:30:00 2.2485 2.2304 2.2409
2 2020-11-10 17:00:00 2.2995 2.2255 2.2790
3 2020-11-10 17:30:00 2.2869 2.2438 2.2554
4 2020-11-10 18:00:00 2.2554 2.2111 2.2111
GetDataProcess Trade Message = None
GetDataProcess Trade Price (Qty: 0.05) = 0
GetDataProcess Data processed and saved to QuantTrending table.
END: v3/klines 30m SOLUSDT GetDataProcess Completed.

START DB Processing: >>> Data from QuantTrending table.
BackTestSharpRatioMDD: >>> Processed the file QuantTrending.csv.
Warning: NaN values detected in ‘Previous_Close’. Attempting to recalculate ‘Daily_PnL’.
Warning: NaN or Infinite values detected in ‘Daily_PnL’ after recomputation. Cleaning required.
Info: Previous_Close Close Daily_PnL Cumm_PnL
count 61663.000000 61663.000000 61663.000000 61663.000000
mean 62.083602 62.086390 0.001621 63.921336
std 58.720934 58.722173 0.007704 26.552746
min 1.101800 1.101800 -0.178662 0.000000
25% 20.810000 20.810000 0.000000 49.072912
50% 33.951000 33.960000 0.000000 72.006780
75% 97.620000 97.620000 0.000000 85.162826
max 258.440000 258.440000 0.200871 99.982746

*> DGM Sharp Ratio = 4.02
**> DGM Maximum Drawdown: 17.87%
***> DGM Peak Profit: 9998.27%
****> DGM Drawdown from Peak: 0.00%
*****>> Created SOLUSDT-QuantSharpRatioMDD-30m.csv for Equity Curve.

Test LWMA Strategy 3:

In summary:

fastEMA:30 slowEMA:50 SOLUSDT SL=2.5, TP=1.8, return=12.76% in 1h.
fastEMA:30 slowEMA:50 SOLUSDT SL=1.6, TP=2.1, return=4.73% in 30m.
fastEMA:30 slowEMA:50 SOLUSDT SL=1.6, TP=2.1, return=4.30% in 30m.

fastWMA:10 slowWMA:34 SOLUSDT SL=1.6, TP=2.1, return=13.84% in 30m.
Beyond the Sharpe Ratio: Unveiling Effective Trading Strategy Assessment

In 1993, Buffett spoke to Columbia University’s Business School graduates. Asked about his method for evaluating risk, he said, “Risk comes from not knowing what you’re doing.” This quote reflects Buffett’s investment philosophy, highlighting the crucial role of knowledge and understanding in reducing risk.

The biggest risk is not taking any risk… In a world that changing really quickly, the only strategy that is guaranteed to fail is not taking risks.” Mark Zuckerberg



Tips:

Despite of the crypto dump recently on all the alt coins after SEC announcement to sue Binance and Coinbase. Guess what? My Ai Trading Strategies are making shit ton of USDT from the crazy markets. Well there is a secret and cannot tell you unless…Anyway, I have given you the formula to copy and it is up to you to trade manually with stress and sleepless nights or ride on the trend of Ai trading today ⬇️⬇️⬇️


AI Sleeping Income With DGM System

The SECRET is to marry between Ai trading strategies and an income generated exchange platform

  • Ai trading strategies

  • An income generated exchange platform

How It Works?


Price Action EMA + RSI + Bollinger Bands With Bots Testing

fastEMA:30 slowEMA:50 SOLUSDT SL=2.5, TP=1.8, return=13.29% in 1h.
fastEMA:30 slowEMA:50 SOLUSDT SL=2.5, TP=1.3, return=4.96% in 30m.
fastEMA:30 slowEMA:50 SOLUSDT SL=1.2, TP=1.1, return=-1.01% in 15m.
fastEMA:30 slowEMA:50 SOLUSDT SL=1.5, TP=2.5, return=-0.42% in 5m.
fastEMA:30 slowEMA:50 SOLUSDT SL=1.1, TP=1.4, return=0.66% in 4h.
fastEMA:20 slowEMA:40 SOLUSDT SL=2.4, TP=2.2, return=6.70% in 1h.
fastEMA:50 slowEMA:100 SOLUSDT SL=2.0, TP=2.5, return=8.82% in 1h.

fastEMA:30 slowEMA:50 ETHUSDT SL=2.1, TP=2.4, return=10.72% in 1h.
fastEMA:30 slowEMA:50 ETHUSDT SL=1.8, TP=1.3, return=1.06% in 30m.
fastEMA:30 slowEMA:50 ETHUSDT SL=1.1, TP=1.7, return=0.10% in 15m.
fastEMA:30 slowEMA:50 ETHUSDT SL=1.3, TP=2.5, return=0.69% in 5m.
fastEMA:30 slowEMA:50 ETHUSDT SL=1.0, TP=1.3, return=3.97% in 4h.
fastEMA:20 slowEMA:40 ETHUSDT SL=2.2, TP=2.4, return=9.95% in 1h.
fastEMA:50 slowEMA:100 ETHUSDT SL=1.3, TP=2.5, return=-2.24% in 1h.

def count_opened_trades():
    api_instance = c.API(access_token)
    config = api_instance.config
    api_key = config.get(“api_key_bybit”)
    api_secret = config.get(“api_secret_bybit”)
    session = HTTP(testnet=False, api_key=api_key, api_secret=api_secret)
    try:
        data = session.get_positions(category=”linear”, symbol=Symbol)
        size = data[‘result’][‘list’][0][‘size’]
        return float(size)
    except Exception as e:
        print(f”DGM Failed to get {Symbol} position: {e}”)
        return

def ema_signal(df, current_candle, backcandles):  
    df_slice = df.reset_index().copy()
    start = max(0, current_candle – backcandles)
    end = current_candle + 1
    relevant_rows = df_slice.iloc[start:end]
   
    # Check if all EMA_fast values are below EMA_slow values (buy signal)
    if (relevant_rows[‘EMA_fast’] < relevant_rows[‘EMA_slow’]).all():
        return 1
    # Check if all EMA_fast values are above EMA_slow values (sell signal)
    elif (relevant_rows[‘EMA_fast’] > relevant_rows[‘EMA_slow’]).all():
        return -1
    else:
        return 0
   
def total_signal(df, current_candle, backcandles):
    if isinstance(current_candle, pd.Timestamp):
        current_candle = df.index.get_loc(current_candle)

    ema_signal_result = ema_signal(df, current_candle, backcandles)

    candle_open_price = df[‘Open’].iloc[current_candle]
    bbl = df[‘BBL_15_1.5’].iloc[current_candle]
    bbu = df[‘BBU_15_1.5’].iloc[current_candle]

    if ema_signal_result == 1 and candle_open_price <= bbl:
        return 1
    if ema_signal_result == -1 and candle_open_price >= bbu:
        return -1
    return 0

def get_candles(symbol, interval, lookback):
    url = f”{API_URLv3}{library}?symbol={symbol}&interval={interval}&limit={lookback}”
    try:
        response = requests.get(url)
        response.raise_for_status()
        data = response.json()

        if not data:
            print(f”No data received from {API_URLv3}{library} API.”)
            return None

        df = pd.DataFrame(data, columns=[
            ‘open_time’, ‘open’, ‘high’, ‘low’, ‘close’, ‘volume’,
            ‘close_time’, ‘quote_asset_volume’, ‘number_of_trades’,
            ‘taker_buy_base_asset_volume’, ‘taker_buy_quote_asset_volume’, ‘ignore’
        ])
        df[‘open_time’] = pd.to_datetime(df[‘open_time’], unit=’ms’)
        df.set_index(‘open_time’, inplace=True)
        df.rename(columns={‘open’: ‘Open’, ‘high’: ‘High’, ‘low’: ‘Low’, ‘close’: ‘Close’}, inplace=True)

        df[[‘Open’, ‘High’, ‘Low’, ‘Close’]] = df[[‘Open’, ‘High’, ‘Low’, ‘Close’]].astype(float)
        return df[[‘Open’, ‘High’, ‘Low’, ‘Close’]]
    except requests.RequestException as e:
        print(f”{symbol} Request failed: {e}”)
    except Exception as e:
        print(f”Failed to process {symbol} data: {e}”)
    return None

def get_candles_frame(lookback):
    candles = get_candles(Symbol, Interval, lookback)

    if candles is None:
        print(f”Failed to retrieve {Interval} {Symbol} candle data.”)
        return None

    dfstream = candles.copy()

    dfstream[‘ATR’] = ta.atr(dfstream[‘High’], dfstream[‘Low’], dfstream[‘Close’], length=7)
    dfstream[‘EMA_fast’] = ta.ema(dfstream[‘Close’], length=30)
    dfstream[‘EMA_slow’] = ta.ema(dfstream[‘Close’], length=50)
    dfstream[‘RSI’] = ta.rsi(dfstream[‘Close’], length=10)
    my_bbands = ta.bbands(dfstream[‘Close’], length=15, std=1.5)
    dfstream = dfstream.join(my_bbands)
    if not isinstance(dfstream.index, pd.DatetimeIndex):
        dfstream.index = pd.to_datetime(dfstream.index)

    dfstream[‘TotalSignal’] = dfstream.apply(lambda row: total_signal(dfstream, row.name, 7), axis=1)
    dfstream.to_csv(‘dfstream.csv’)
    return dfstream

def optimization():
    slatrcoef = 0
    TPSLRatio_coef = 0

    dfstream = get_candles_frame(lookback)
    if dfstream is None:
        print(f”No candle data for {Symbol} fitting optimization job.”)
        return

    def SIGNAL():
        return dfstream[‘TotalSignal’]

    class MyStrat(Strategy):
        mysize = 3000
        slcoef = 1.3
        TPSLRatio = 2.5

        def init(self):
            self.signal1 = self.I(SIGNAL)

        def next(self):
            slatr = self.slcoef * self.data.ATR[-1]
            TPSLRatio = self.TPSLRatio

            if self.signal1[-1] == 2 and len(self.trades) == 0:
                sl1 = self.data.Close[-1] – slatr
                tp1 = self.data.Close[-1] + slatr * TPSLRatio
                self.buy(sl=sl1, tp=tp1, size=self.mysize)

            elif self.signal1[-1] == 1 and len(self.trades) == 0:
                sl1 = self.data.Close[-1] + slatr
                tp1 = self.data.Close[-1] – slatr * TPSLRatio
                self.sell(sl=sl1, tp=tp1, size=self.mysize)

    bt = Backtest(dfstream, MyStrat, cash=100000, margin=0.01, commission=0.00055)
    stats, heatmap = bt.optimize(slcoef=[i/10 for i in range(10, 26)],
                                 TPSLRatio=[i/10 for i in range(10, 26)],
                                 maximize=’Return [%]’, max_tries=300,
                                 random_state=0,
                                 return_heatmap=True)
    print(stats)
   
    slatrcoef = stats[“_strategy”].slcoef
    TPSLRatio_coef = stats[“_strategy”].TPSLRatio
    print(f”{Symbol} SL = {slatrcoef}, TP = {TPSLRatio_coef}, expected return, {stats[‘Return [%]’]:.2f}% in {Interval} interval.\n”)
   
    with open(“fitting_data_file.txt”, “a”) as file:
        file.write(f”{Symbol} SL = {slatrcoef}, TP = {TPSLRatio_coef}, expected return, {stats[‘Return [%]’]:.2f}% in {Interval} interval.\n”)
    return slatrcoef, TPSLRatio_coef

def trading_job():
    dfstream = get_candles_frame(lookback)
    if dfstream is None:
        print(f”No {Symbol} candle data for trading job.”)
        return

    signal = total_signal(dfstream, len(dfstream) – 1, 7)



    # now = datetime.now()
    # if now.weekday() == 0 and now.hour < 7 and now.minute < 5:  # Monday before 07:05
    slatrcoef, TPSLRatio_coef = optimization()
    print(f”Optimize SL = {slatrcoef}, and TP = {TPSLRatio_coef}.”)

    slatr = slatrcoef * dfstream[‘ATR’].iloc[-1]
    TPSLRatio = TPSLRatio_coef
    max_spread = 16e-5

    last_candle = get_candles(Symbol, Interval, 1).iloc[-1]
    candle_open_bid = float(last_candle[‘Open’])
    candle_open_ask = candle_open_bid
    spread = candle_open_ask – candle_open_bid

    SLBuy = candle_open_bid – slatr – spread
    SLSell = candle_open_ask + slatr + spread

    TPBuy = candle_open_ask + slatr * TPSLRatio + spread
    TPSell = candle_open_bid – slatr * TPSLRatio – spread

    print(“SLBuy = “, SLBuy)
    print(“SLSell = “, SLSell)
    print(“TPBuy  = “, TPBuy )
    print(“TPSell = “, TPSell)
   
    # # Sell
    # if signal == -1 and count_opened_trades() == 0.0 and spread < max_spread:
    #     print(“Sell Signal Found…”)
    #     trade_crypto = c.TradeCrypto(EXCHANGE, Symbol, ‘sell’)
    #     message, MyTradePrice = trade_crypto.TradeQty(quantity)
    #     print(message)
    #     with open(“trading_data_file.txt”, “a”) as file:
    #         file.write(f”SL = {SLSell}, TP = {TPSell}, Trade Price = {MyTradePrice}\n”)

    # # Buy
    # elif signal == 1 and count_opened_trades() == 0.0 and spread < max_spread:
    #     print(“Buy Signal Found…”)
    #     trade_crypto = c.TradeCrypto(EXCHANGE, Symbol, ‘buy’)
    #     message, MyTradePrice = trade_crypto.TradeQty(quantity)
    #     print(message)
    #     with open(“trading_data_file.txt”, “a”) as file:
    #         file.write(f”SL = {SLBuy}, TP = {TPBuy}, Trade Price = {MyTradePrice}\n”)


if __name__ == “__main__”:
    optimization()

# scheduler = BlockingScheduler()
# scheduler.add_job(trading_job, ‘cron’, day_of_week=’mon-fri’, hour=’07-18′, minute=’1, 6, 11, 16, 21, 26, 31, 36, 41, 46, 51, 56′, timezone=’Asia/Beirut’, misfire_grace_time=15)
# scheduler.start()

In 1993, Buffett spoke to Columbia University’s Business School graduates. Asked about his method for evaluating risk, he said, “Risk comes from not knowing what you’re doing.” This quote reflects Buffett’s investment philosophy, highlighting the crucial role of knowledge and understanding in reducing risk.

The biggest risk is not taking any risk… In a world that changing really quickly, the only strategy that is guaranteed to fail is not taking risks.” Mark Zuckerberg



Tips:

Despite of the crypto dump recently on all the alt coins after SEC announcement to sue Binance and Coinbase. Guess what? My Ai Trading Strategies are making shit ton of USDT from the crazy markets. Well there is a secret and cannot tell you unless…Anyway, I have given you the formula to copy and it is up to you to trade manually with stress and sleepless nights or ride on the trend of Ai trading today ⬇️⬇️⬇️


AI Sleeping Income With DGM System

The SECRET is to marry between Ai trading strategies and an income generated exchange platform

  • Ai trading strategies

  • An income generated exchange platform

How It Works?