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?


@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?


The most fantastic experience, a divine man who has been buried for thirty-eight years

目前為止最長的影片,最奇幻的經歷,一個被埋沒了三十八年的神人
你的人生將充滿幸福和快樂
解讀它將改變你的人生

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?


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?


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?


BackTest Sharpe Ratio and Max Draw Down

DGM Sharp Ratio = 3.5

2024-05-14 09:01:09,378 – INFO – DGM Start Date and Time now is 2024-05-14 09:01:09.378769
2024-05-14 09:01:09,880 – INFO – All data downloaded successfully in GetDataRequest.
2024-05-14 09:01:09,993 – INFO – Exported FROM 2020-11-11 TO 2024-05-14 Data saved to DB.
2024-05-14 09:01:10,401 – INFO – File QuantTrending.csv has been successfully deleted.
2024-05-14 09:01:10,401 – INFO – >>*>> ETHUSDT-QuantSharpRatioMDD-1d.csv for Equity Curve.
2024-05-14 09:01:10,401 – INFO – BackTest Trade Message = None
2024-05-14 09:01:10,401 – INFO – BackTest Trade Price (Qty: 0.05) = 0
DGM Class Start Date and Time now is 2024-05-14 09:01:09.380486
START: 1d ETHUSDT OHLC-data from 2020-11-11 00:00:00 until 2024-05-14
Open Time Open High Low Close
0 2020-11-11 450.34 476.25 449.28 463.09
1 2020-11-12 463.09 470.00 451.20 462.39
2 2020-11-13 462.48 478.01 457.12 476.43
3 2020-11-14 476.42 477.47 452.00 460.89
4 2020-11-15 460.90 462.89 440.19 448.08
.. … … … … …
276 2024-05-10 3036.24 3053.89 2878.03 2909.99
277 2024-05-11 2909.98 2945.67 2886.46 2912.45
278 2024-05-12 2912.45 2955.20 2901.17 2929.29
279 2024-05-13 2929.30 2996.40 2864.76 2950.99
280 2024-05-14 2950.99 2958.76 2937.51 2944.75

[1281 rows x 5 columns]
END: v3/klines 1d ETHUSDT DB Processed.

START DB Processing: >>> Data from GetDataRequested table.
Mean Price: 2208.228266978923
Standard Deviation: 914.490172178236
v3/klines Upper Percentage Threshold: 4037.208611335395
v3/klines Lower Percentage Threshold: 379.2479226224509
Open Time High Low Close
0 2020-11-11 476.25 449.28 463.09
1 2020-11-12 470.00 451.20 462.39
2 2020-11-13 478.01 457.12 476.43
3 2020-11-14 477.47 452.00 460.89
4 2020-11-15 462.89 440.19 448.08
GetDataProcess Trade Message = None
GetDataProcess Trade Price (Qty: 0.05) = 0
GetDataProcess Data processed and saved to QuantTrending table.
END: v3/klines 1d ETHUSDT 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 1280.000000 1280.000000 1280.000000 1280.000000
mean 2207.652859 2209.591656 0.014513 11.073642
std 914.972973 913.902063 0.038246 5.210313
min 448.080000 448.080000 -0.263329 0.000000
25% 1598.405000 1599.225000 -0.000000 7.088900
50% 1899.325000 1900.090000 -0.000000 12.360589
75% 2910.605000 2914.057500 0.031202 15.726248
max 4807.980000 4807.980000 0.277372 18.590075

*> DGM Sharp Ratio = 7.25
**> DGM Maximum Drawdown: 28.47%
***> DGM Peak Profit: 1859.01%
****> DGM Drawdown from Peak: 1.40%
*****>> Created ETHUSDT-QuantSharpRatioMDD-1d.csv for Equity Curve.

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?


DGM Trading AI Processes, Procedures and Results

AI Processes and Procedures

Some Trading Factors Used by AI or bots

What does this mean?




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 Candles Pattern Scanner


Closing-Marubozu-Pattern



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?