Forum Replies Created

Check out all your contributions and responses across the community.

Viewing 15 posts - 76 through 90 (of 93 total)
  • Author
    Posts
  • Yes, to solve this We have a specific feature for this called LTP Entry Trigger.

    See for this we have the LTP entry what it does basically instead of direct entry, we will have the option that we can make the entry based on LTP.

    so, if we set trigger to 100 then when the LTP reaches to 100 our platform enters the trade and immediately starts watching your Target (if you set suppose = ₹120) and Stop Loss (if you set suppose = ₹90) for you.

    So that’s how we will solve this problem. For more you can explore our app.

    You are right some brokers doesn’t give the direct per-tick volume we have to calculate that by comparing the tick cumulative volume with previous candle stored volume.

    So, like that we will have to convert volume manually.

    Below logic and code, you can refer.

    Delta Volume = Current Volume – Previous Volume
    Below code that you can refer:

    def calculate_delta_volume(ticks):
        prev_volume = None
        result = []
        for tick in ticks:
            current_volume = tick["volume"]
            if prev_volume is None:
                delta = 0  # first tick
            else:
                delta = current_volume - prev_volume
    
                # safety check (in case of reset or bad data)
                if delta < 0:
                    delta = 0
            tick["delta_volume"] = delta
            result.append(tick)
            prev_volume = current_volume
        return result
    
    # usage
    ticks = [
        {"price": 100, "volume": 1000},
        {"price": 101, "volume": 1200},
        {"price": 102, "volume": 1500},
    ]
    
    output = calculate_delta_volume(ticks)
    
    for t in output:
        print(t)

    Later can use in the building candles from live data.

    Yeah, this will happen in WebSocket because we have to send the heartbeat (ping) or reconnect logic.

    You need 2 things:

    Heartbeat (to detect dead connection)

    Auto-reconnect logic

    Below is the sample code you can refer:

    import time
    import threading
    
    last_tick_time = time.time()
    RECONNECT_TIMEOUT = 5  # seconds
    
    def on_tick(tick):
        global last_tick_time
        last_tick_time = time.time()
        print("Tick:", tick)
    
    def start_socket():
        print("Starting WebSocket...")
        # Actuall broket connect code
        # ws.connect()
    
    def stop_socket():
        print("Stopping WebSocket...")
        # Actual close
        # ws.close()
    
    def reconnect():
        print("Reconnecting...")
        stop_socket()
        time.sleep(1)
        start_socket()
    
    def heartbeat_checker():
        while True:
            time.sleep(1)
            if time.time() - last_tick_time > RECONNECT_TIMEOUT:
                print("No ticks received. Connection seems dead.")
                reconnect()
    
    # Start everything
    start_socket()
    
    threading.Thread(target=heartbeat_checker, daemon=True).start()
    
    # Simulated tick loop
    while True:
        time.sleep(2)
        on_tick({"price": 100})

    Since, websocket are not 100 percent reliabile we need the heartbit or reconnect logic.

    Yes, this will happen in the one minute candle data is used from the historical data.

    Because, Camarilla (and most pivots) should not be calculated from one minute candles.

    Correct approach:

    You have to calculate pivot in the previous full day candle not the previous day one-minute candles.

    Because the last candle close in the minute candle is different from the previous full day candle – just slightly different of some points but still the values in pivot will be inaccurate.

    Below is the code that you can refer:

    def camarilla_pivot(prev_high, prev_low, prev_close):
        diff = prev_high - prev_low
        
        levels = {
            "H1": prev_close + (diff * 1.1 / 12),
            "H2": prev_close + (diff * 1.1 / 6),
            "H3": prev_close + (diff * 1.1 / 4),
            "H4": prev_close + (diff * 1.1 / 2),
            "PP": (prev_high + prev_low + prev_close) / 3.0,
            "L1": prev_close - (diff * 1.1 / 12),
            "L2": prev_close - (diff * 1.1 / 6),
            "L3": prev_close - (diff * 1.1 / 4),
            "L4": prev_close - (diff * 1.1 / 2),
        }
    
        return levels
    
    # Example (use previous day data of 1 day timeframe candle)
    prev_high = 200
    prev_low = 180
    prev_close = 190
    
    levels = camarilla_pivot(prev_high, prev_low, prev_close)
    print(levels)

    Ok, so don’t hardcode strikes — you calculate them using spot price and stick gap (step size).

    As each stock has different strike gaps
    ATM is just nearest rounded strike
    ITM/OTM = shift from ATM
    Simple approach in steps:

    Get latest spot price
    Round to nearest strike gap → ATM
    Add/subtract gap → ITM/OTM
    Can also refer the example code below:

    def get_strikes(spot, strike_gap):
        atm = round(spot / strike_gap) * strike_gap
    
        strikes = {
            "ATM": atm,
            "OTM_CE": atm + strike_gap,
            "ITM_CE": atm - strike_gap,
            "OTM_PE": atm - strike_gap,
            "ITM_PE": atm + strike_gap,
        }
    
        return strikes
    
    # Sample
    spot_price = 19876 # Since spot price from the socket
    strike_gap = 50  # NIFTY = 50, BANKNIFTY = 100
    
    strikes = get_strikes(spot_price, strike_gap)
    
    print(strikes)

    Yes, so there’s no direct API that gives you “strike gap”.

    The one way to do that calculate it from available strikes from the any source like script master file.

    So, the simple idea is Strike gap = difference between consecutive strikes

    Can understand with simple steps:

    Fetch option chain / instruments
    Take available strikes
    Sort them
    Find difference
    Can also refer below code:

    def get_strike_gap(strikes):
        strikes = sorted(set(strikes))
        if len(strikes) < 2:
            return None
        gaps = [strikes[i+1] - strikes[i] for i in range(len(strikes)-1)]
        # Most common gap
        gap = min(gaps)
        return gap
    
    # Sample - Inplace of this have the stricks from instrument/option chain
    strikes = [19800, 19850, 19900, 19950, 20000]
    
    gap = get_strike_gap(strikes)
    print("Strike Gap:", gap)

    See in high volatility, the price “gaps” down. If your SL is a Limit order at 100, and the price jumps from 102 to 98, your order will never fill because the price is already below your limit.

    This is because of the:

    Price Gapping: In fast markets, the LTP (Last Traded Price) skips your specific Limit price.

    SL-L vs SL-M: SL-Limit (SL-L) requires a specific price match. SL-Market (SL-M) triggers as soon as the price is hit, but many brokers now restrict SL-M for Options to prevent “freak trades.”

    Fix is you have to use a range for SL – Limit orders, use wide difference between your Trigger Price and your Limit Price.

    Another fix is buffer set trigger at your exit point but set Limit much lower to ensure it acts like a market order within a protected range.

    def place_protected_sl(current_price, sl_points, is_buy=False):
        # Example for an existing BUY position (so we place a SELL SL)
        trigger_price = current_price - sl_points
        
        # Set limit price 1% lower than trigger to ensure execution in a crash
        # This creates a "price range" for the fill
        limit_price = round(trigger_price * 0.99, 1)
        
        order_params = {
            "symbol": "NIFTY25JAN22500CE",
            "qty": 50,
            "type": "STOPLOSS_LIMIT",
            "side": "SELL",
            "trigger_price": trigger_price,
            "price": limit_price # The "worst" price you'll accept
        }
        
        return order_params
    
    # Input: Bought at 100, SL at 90
    sl_order = place_protected_sl(100, 10)
    print(f"Trigger: {sl_order['trigger_price']} | Limit: {sl_order['price']}")
    # Result: Trigger 90, Limit 89.1 -> Order fills anywhere between 90 and 89.1

    So, you can find it from the instrument list provided by broker.

    Root idea is that broker gives the full instrument data (CSV/list).

    We can filter it based on symbol, Strick, expire, option type (CE/PE).

    So, the logic is simple we will select the most common Strick gap.

    Below is the code you can refer:

    def find_option(instruments, name, strike, option_type):
        filtered = []
        for ins in instruments:
            if (
                ins["name"] == name and
                ins["instrument_type"] == option_type and
                ins["strike"] == strike
            ):
                filtered.append(ins)
        if not filtered:
            return None
        # pick nearest expiry
        filtered.sort(key=lambda x: x["expiry"])
        return filtered[0]
    
    # Sample instrument data
    instruments = [
        {"name": "NIFTY", "strike": 19900, "instrument_type": "CE", "expiry": "2026-04-30", "token": 111},
        {"name": "NIFTY", "strike": 19900, "instrument_type": "CE", "expiry": "2026-05-07", "token": 222},
    ]
    
    result = find_option(instruments, "NIFTY", 19900, "CE")
    
    print(result)

    Yes, this may be the issue of data consistency.

    See may be the problem because of these factors:

    Calculation on incomplete candles
    Missing initial historical data.
    Candle mismatch because of timing

    See we need the both the live and historical data to get the accurate values in EMA and SMA.

    Below is the code that you can refer:

    def calculate_ema(prices, period=5):
        ema = []
        k = 2 / (period + 1)
    
        for i, price in enumerate(prices):
            if i == 0:
                ema.append(price)
            else:
                ema.append(price * k + ema[-1] * (1 - k))
    
        return ema
    
    # This prices should be have the both live and historical data
    prices = [100, 102, 101, 105, 107, 110]
    
    ema_values = calculate_ema(prices, period=3)
    print(ema_values)

    Yes, the rate limit varies from broker to broker (e.g.: Zeroth 3req/sec)

    This happens in almost every broker if we hit the API in the loop continuously.

    To solve this problem, you have to put the delay, if possible, of approx. 0.30 sec,

    also, we can do the batch fetching – hit the API in batch

    Below sample code you can refer:

    import time
    
    def fetch_all_data(symbols, fetch_func):
        data = {}
    
        for i, symbol in enumerate(symbols):
            try:
                data[symbol] = fetch_func(symbol)
                print(f"Fetched: {symbol}")
    
                # small delay to avoid rate limit
                time.sleep(0.5)
    
            except Exception as error:
                print(f"Failed: {symbol} -> {error}")
    
        return data
    
    # Sample
    def mock_fetch(symbol):
        return f"data_for_{symbol}"
    
    symbols = ["AAPL", "MSFT", "GOOG", "TSLA"]
    
    result = fetch_all_data(symbols, mock_fetch)
    
    print(result)

    Yes, so the solution that we provided in AlgoDelta is we can modify the order if the price changes.

    So, it’s like telling the exchange that “I want to buy up to this high price,” which effectively fills you instantly at the best available seller’s price, just like a Market order, but with a “safety cap.”. For more you can explore the more feature or contact support.

    You definitely do not need to manage 3 separate alerts. In our AlgoDelta platform, we have built a Grouping & Multiplier system specifically for this scenario.

    So clear solution in below steps:

    In the AlgoDelta dashboard, go to the “Group” section and add all 3 of your demat accounts into a single group

    Assign Multipliers: Set a multiplier for each account based on capital:

    Broker 1 : Multiplier 1 (Base) – Keep the base account in which have the less fund

    Broker 2 : Multiplier 2

    Broker 3 : Multiplier 3

    Single Webhook: Set up only one alert in TradingView pointing to your AlgoDelta Strategy Key.

    Even algoDelta fires orders to all 3 brokers at the same millisecond, so you get the same entry price across all accounts.

    Yes, every broker has their own “language” for symbols.

    In AlgoDelta, we solved this with our Universal Symbol Mapping engine. User don’t need to worry about tokens or specific broker formats anymore.

    User just have to select in which script they want to trade the symbol and token that we automatically managed by our platform AlgoDelta. You can explore more feature that automate your script trades.

    Yes, with AlgoDelta, you don’t have to worry about that. You can group accounts together, and once they’re grouped, a single action fires the order across all of them simultaneously.

    So instead of managing accounts one after another all orders go out almost at the same time you get consistent execution for everyone.

    In short, you just create a group and trade — the system takes care of syncing the execution.

    Yes, for sure we have this kind of the feature that is group management – so basically you can put all the different trades as you mension like Nifty and BankNifty into that group.

    Now you can set the combine target so no matter of the individual script if the combine profit reaches target then the both the position will be exited automatically. For more you can explore our app.

Viewing 15 posts - 76 through 90 (of 93 total)
×

Start a Discussion

Get help from the AlgoDelta community.

×

Welcome Back!

Enter your email to sign in or create an account. No passwords needed.

Pending Approval

⚠️

Delete This?

Are you sure you want to delete this? This action is permanent and cannot be undone.

Scroll to Top