Skip to content

Streak me strategy laga kar streak me alag se dikh jaay  #205

@harishmadaan65-lgtm

Description

@harishmadaan65-lgtm

from kiteconnect import KiteConnect
import pandas as pd
import numpy as np
import datetime

Zerodha API Credentials

api_key = s57ekpdsxxu6a1x4ldapvafx7lb1j1kj
api_secret = pom72uaolkby7us4
access_token = 237965
kite = KiteConnect s57ekpdsxxu6a1x4ldapvafx7lb1j1kj
kite.set_access_token 011648

Parameters

symbol = "NSE:RELIANCE" # Example: Reliance
quantity = 1
target_percent = 5 # 5% Daily Target
stop_loss_percent = 2 # 2% Stop-Loss

Fetch Historical Data

def fetch_historical_data(symbol, days=5):
end_date = datetime.datetime.now()
start_date = end_date - datetime.timedelta(days=days)
interval = "15minute" # You can change to 5minute/1hour/day
data = kite.historical_data(
instrument_token=kite.ltp(symbol)[symbol]["instrument_token"],
from_date=start_date,
to_date=end_date,
interval=interval,
)
df = pd.DataFrame(data)
df["date"] = pd.to_datetime(df["date"])
df.set_index("date", inplace=True)
return df

Moving Average Crossover Strategy

def moving_average_strategy(df, short_window=5, long_window=20):
df["short_ma"] = df["close"].rolling(window=short_window).mean()
df["long_ma"] = df["close"].rolling(window=long_window).mean()
df["signal"] = np.where(df["short_ma"] > df["long_ma"], 1, -1) # 1=Buy, -1=Sell
return df

Execute Trade

def execute_trade(signal, symbol, quantity):
ltp = kite.ltp(symbol)[symbol]["last_price"]
if signal == 1: # Buy
target_price = ltp * (1 + target_percent / 100)
stop_loss_price = ltp * (1 - stop_loss_percent / 100)
print(f"BUY ORDER: {symbol} at {ltp}")
print(f"Target: {target_price}, Stop-Loss: {stop_loss_price}")
# Uncomment below to place real order
# kite.place_order(
# tradingsymbol=symbol.split(":")[1],
# exchange=symbol.split(":")[0],
# transaction_type="BUY",
# quantity=quantity,
# order_type="LIMIT",
# price=ltp,
# product="MIS",
# validity="DAY",
# )
elif signal == -1: # Sell
target_price = ltp * (1 - target_percent / 100)
stop_loss_price = ltp * (1 + stop_loss_percent / 100)
print(f"SELL ORDER: {symbol} at {ltp}")
print(f"Target: {target_price}, Stop-Loss: {stop_loss_price}")
# Uncomment below to place real order
# kite.place_order(
# tradingsymbol=symbol.split(":")[1],
# exchange=symbol.split(":")[0],
# transaction_type="SELL",
# quantity=quantity,
# order_type="LIMIT",
# price=ltp,
# product="MIS",
# validity="DAY",
# )

Main Algo Logic

def run_algo():
df = fetch_historical_data(symbol)
df = moving_average_strategy(df)
latest_signal = df["signal"].iloc[-1]
execute_trade(latest_signal, symbol, quantity)

if name == "main":
run_algo() Rakhi strategy

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions