Request to support Kite API Support on GTT faild.

SanjuMMT611
Hello Zerodha API,

Hope you are well,

I'm using Kite API to place orders and GTT using C# programming.

Today I placed orders and GTT, it was placed successfully, but when my stop loss was about to trigger that time my stop loss GTT failed.

Could you diagnose why it failed and how to fix it.

Stock details
1. LTP = 887.2
2. Stop loss = 884.95
3. Target price = 904.95
4. Lower circuit price = 628.90

logs details are
While place orders

"Enter Trading Symbol value
ARROWGREEN
Stock Details:
{"InstrumentToken":2370561,"LastPrice":887.2,"LastQuantity":1,"AveragePrice":870.68,"Volume":234859,"BuyQuantity":45069,"SellQuantity":70705,"Open":850,"High":903.55,"Low":835.05,"Close":786.1,"Change":0,"LowerCircuitLimit":628.9,"UpperCircuitLimit":943.3,"Bids":[{"Quantity":61,"Price":885.55,"Orders":3},{"Quantity":19,"Price":885.5,"Orders":2},{"Quantity":6,"Price":885.45,"Orders":1},{"Quantity":6,"Price":885.4,"Orders":1},{"Quantity":11,"Price":885.3,"Orders":3}],"Offers":[{"Quantity":72,"Price":887.2,"Orders":1},{"Quantity":48,"Price":887.25,"Orders":4},{"Quantity":40,"Price":888.35,"Orders":1},{"Quantity":18,"Price":888.4,"Orders":1},{"Quantity":8,"Price":888.45,"Orders":2}],"LastTradeTime":"2024-08-05T09:16:44","OI":0,"OIDayHigh":0,"OIDayLow":0,"Timestamp":"2024-08-05T09:16:44"}
LastPrice: 887.2, MinStopLoss: 2.22000, CalculatedStopLoss: 884.95, Target: 904.95
Buy Order Id: 240805300154049
GTT Order Id: System.Collections.Generic.Dictionary`2[System.String,System.Object]
GTT Details:
{"Id":230354856,"Condition":{"InstrumentToken":2370561,"Exchange":"NSE","TradingSymbol":"ARROWGREEN","TriggerValues":[884.95,904.95],"LastPrice":887.2},"TriggerType":"two-leg","Orders":[{"TransactionType":"SELL","Product":"CNC","OrderType":"SL-M","Quantity":2,"Price":884.95,"Result":null},{"TransactionType":"SELL","Product":"CNC","OrderType":"LIMIT","Quantity":2,"Price":904.95,"Result":null}],"Status":"active","CreatedAt":"2024-08-05T09:16:46","UpdatedAt":"2024-08-05T09:16:46","ExpiresAt":"2025-08-05T09:16:46","Meta":{"RejectionReason":""}}"

image.png


image.png

and my code details
private static int SetStopLossAndTargetPrice(string tradingSymbol, decimal lastPrice, decimal stopLossPrice, decimal targetPrice, int quantity)
{
var triggerId = 0;
GTTParams gttParams = new GTTParams
{
TriggerType = Constants.GTT_TRIGGER_OCO,
Exchange = "NSE",
TradingSymbol = tradingSymbol,
LastPrice = lastPrice
};

gttParams.TriggerPrices = new List { stopLossPrice, targetPrice };

var stopLossOrder = new GTTOrderParams
{
OrderType = Constants.ORDER_TYPE_SLM,
Price = stopLossPrice,
Product = Constants.PRODUCT_CNC,
TransactionType = Constants.TRANSACTION_TYPE_SELL,
Quantity = quantity
};

var targetOrder = new GTTOrderParams
{
OrderType = Constants.ORDER_TYPE_LIMIT,
Price = targetPrice,
Product = Constants.PRODUCT_CNC,
TransactionType = Constants.TRANSACTION_TYPE_SELL,
Quantity = quantity
};

gttParams.Orders = new List { stopLossOrder, targetOrder };

var placeGTTResponse = kite.PlaceGTT(gttParams);
Console.WriteLine("GTT Order Id: " + placeGTTResponse);

if (placeGTTResponse["status"] == "success")
{
triggerId = Convert.ToInt32(placeGTTResponse["data"]["trigger_id"]);
GetGTTDetails(triggerId);
}
else
{
Console.WriteLine("================== GTT failed ======");
Console.WriteLine(Utils.JsonSerialize(placeGTTResponse));
}
return triggerId;
}

private static void PlaceBuyOrder(string tradingSymbol, int quantity, decimal lastPrice)
{
//Place Buy Order
Dictionary buyOrderResponse = kite.PlaceOrder(
Exchange: Constants.EXCHANGE_NSE,
TradingSymbol: tradingSymbol,
TransactionType: Constants.TRANSACTION_TYPE_BUY,
Quantity: quantity,
Price: lastPrice,
OrderType: Constants.ORDER_TYPE_LIMIT,
Product: Constants.PRODUCT_CNC
);
string buyOrderId = buyOrderResponse["data"]["order_id"];
Console.WriteLine("Buy Order Id: " + buyOrderId);

}

public class TradingStrategy
{
public decimal LastPrice { get; set; }
public decimal TickSize { get; set; }
public decimal LowerCircuitLimit { get; set; }

public (decimal StopLoss, decimal Target) CalculateStopLossAndTarget()
{
decimal stopLoss;
decimal target;
decimal minStopLoss;
decimal buffer = 0.002m; // Adding a small buffer to ensure compliance

// Determine the minimum stop-loss based on the last price
if (LastPrice <= 50)
{
minStopLoss = 0.09m + buffer;
}
else
{
minStopLoss = LastPrice * 0.0025m + buffer; // 0.25% of the last price
}

// Calculate the stop-loss and ensure it respects the minimum stop-loss
stopLoss = LastPrice - minStopLoss;
stopLoss = Math.Floor(stopLoss / TickSize) * TickSize;

// Ensure the stop-loss is above the lower circuit price
if (stopLoss < LowerCircuitLimit)
{
stopLoss = Math.Ceiling(LowerCircuitLimit / TickSize) * TickSize;
}

// Calculate the target price and adjust for tick size
target = LastPrice * 1.02m;
target = Math.Ceiling(target / TickSize) * TickSize;

// Logging or comments for better understanding and maintenance
Console.WriteLine($"LastPrice: {LastPrice}, MinStopLoss: {minStopLoss}, CalculatedStopLoss: {stopLoss}, Target: {target}");

return (stopLoss, target);
}
}

public static int BuyShareAndSetStoplossAndTargetPrice(out int returnQuantity)
{
decimal totalAvilableAmount = 0;
int quantity = 0;
string exchange = "NSE";
string tradingSymbol = "";
Console.WriteLine("Enter Trading Symbol value");
tradingSymbol = Console.ReadLine().Trim();


Dictionary<string, Quote> quotes = GetStockDetails(tradingSymbol, exchange);

var stockQuote = quotes[$"{exchange}:{tradingSymbol}"];
decimal lastPrice = stockQuote.LastPrice;
decimal tickSize = GetTickSizeAsync(tradingSymbol);
var strategy = new TradingStrategy
{
LastPrice = lastPrice,
TickSize = tickSize, // Example tick size, adjust as needed
LowerCircuitLimit = stockQuote.LowerCircuitLimit
};
var result = strategy.CalculateStopLossAndTarget();


// Now you can fetch margins
UserMargin equityMargins = kite.GetMargins(Constants.MARGIN_EQUITY);

// totalAvilableAmount = equityMargins.Available.IntradayPayin;

totalAvilableAmount = equityMargins.Available.Cash;
if (totalAvilableAmount != 0)
{
quantity = (int)(totalAvilableAmount / lastPrice);

// quantity = 1;
}



// Place buy order
PlaceBuyOrder(tradingSymbol, quantity, lastPrice);


////Set Stop Loss and Target Price using GTT
var gttTriggerId = SetStopLossAndTargetPrice(tradingSymbol, lastPrice, result.StopLoss, result.Target, quantity);

//Set returnQuantity to return back.
returnQuantity = quantity;
return gttTriggerId;
}
Sign In or Register to comment.