The sample code below demonstrates a simplified Python code for creating a strategy on Kite API based on Moving Averages Crossover strategy. Please note that this example is for educational purposes only and using it in live trading should be done with extreme caution and proper testing.
import pandas as pd
import datetime as dt
from kiteconnect import KiteConnect
import time
# API credentials
api_key = "your_api_key"
api_secret = "your_api_secret"
# Access token obtained after authentication
access_token = "your_access_token"
# Initialize KiteConnect
kite = KiteConnect(api_key=api_key)
kite.set_access_token(access_token)
# Fetch historical data for a stock (Example: NIFTY 50) on 5-minute intervals
symbol = "NSE:NIFTY50"
interval = "5minute" # Fetch data at 5-minute intervals
from_date = "2023-01-01"
to_date = "2023-01-31"
# Initialize position and capital
position = 0
entry_price = 0
capital = 100000 # Example initial capital in INR
stop_loss_pct = 0.5 # Stop loss percentage
target_pct = 1.0 # Target percentage
while True:
try:
data = kite.historical_data(symbol, interval, from_date, to_date)
df = pd.DataFrame(data)
# Calculate 50-period (5 minutes * 50 = 250 minutes) and 200-period (5 minutes * 200 = 1000 minutes) moving averages
df['ma_50'] = df['close'].rolling(window=50).mean()
df['ma_200'] = df['close'].rolling(window=200).mean()
# Implement Moving Averages Crossover strategy
df['signal'] = 0
df.loc[df['ma_50'] > df['ma_200'], 'signal'] = 1
df.loc[df['ma_50'] < df['ma_200'], 'signal'] = -1
current_time = dt.datetime.now().time()
# Check if current time is within the trading hours (9:15 AM to 3:30 PM)
if dt.time(9, 15) <= current_time <= dt.time(15, 30):
if df['signal'].iloc[-1] == 1 and position == 0:
# Buy if no existing position
quantity = capital // df['close'].iloc[-1] # Calculate the number of shares to buy
kite.place_order(tradingsymbol=symbol, exchange="NSE", transaction_type="BUY",
quantity=quantity, order_type="MARKET", product="CNC")
position = 1
entry_price = df['close'].iloc[-1]
print(f"Buy {quantity} shares at {entry_price}")
elif df['signal'].iloc[-1] == -1 and position == 1:
# Sell if there is an existing long position
quantity = capital // df['close'].iloc[-1] # Calculate the number of shares to sell
kite.place_order(tradingsymbol=symbol, exchange="NSE", transaction_type="SELL",
quantity=quantity, order_type="MARKET", product="CNC")
position = 0
print(f"Sell {quantity} shares at {df['close'].iloc[-1]}")
# Check if stop loss or target is hit
if position == 1:
stop_loss_price = entry_price - (entry_price * stop_loss_pct / 100)
target_price = entry_price + (entry_price * target_pct / 100)
if df['low'].iloc[-1] <= stop_loss_price:
# Sell to execute stop loss
quantity = capital // df['close'].iloc[-1] # Calculate the number of shares to sell
kite.place_order(tradingsymbol=symbol, exchange="NSE", transaction_type="SELL",
quantity=quantity, order_type="MARKET", product="CNC")
position = 0
print(f"Stop loss triggered. Sell {quantity} shares at {df['close'].iloc[-1]}")
elif df['high'].iloc[-1] >= target_price:
# Sell to execute target
quantity = capital // df['close'].iloc[-1] # Calculate the number of shares to sell
kite.place_order(tradingsymbol=symbol, exchange="NSE", transaction_type="SELL",
quantity=quantity, order_type="MARKET", product="CNC")
position = 0
print(f"Target achieved. Sell {quantity} shares at {df['close'].iloc[-1]}")
# Sleep for 5 minutes before the next iteration
time.sleep(300)
except Exception as e:
print("An error occurred:", e)
# End of continuous loop
print("Trading strategy stopped.")
Code Explanation
The above Python code is a simple automated trading strategy that uses the Moving Averages Crossover strategy with stop-loss and target conditions to trade NIFTY 50 on 5-minute intervals. The strategy is implemented using the KiteConnect API to interact with the stock market and execute buy/sell orders.
Here’s a step-by-step explanation of the code:
Import Required Libraries:
- pandas: For data manipulation using DataFrames.
- datetime: For handling dates and times.
- KiteConnect: The KiteConnect class from the Kite API for interacting with the stock market.
- time: For introducing delays between iterations.
Define API Credentials and Access Token:
- You need to replace
"your_api_key"
,"your_api_secret"
, and"your_access_token"
with your actual API credentials and access token, which you obtain after authentication.
Fetch Historical Data:
- The code fetches historical data for the NIFTY 50 index for a specified date range (from
from_date
toto_date
) on 5-minute intervals.
Initialize Position and Capital:
position
: A variable that tracks the current position in the market (0 for no position, 1 for long position).entry_price
: The price at which the long position was entered.capital
: The initial capital available for trading (e.g., 100000 INR).
Define Stop Loss and Target Percentages:
stop_loss_pct
: The percentage (0.5%) used to calculate the stop-loss price.target_pct
: The percentage (1.0%) used to calculate the target price.
Continuous Trading Loop:
- The code runs in an infinite while True loop, allowing the strategy to run continuously.
Strategy Execution
- The loop fetches historical data, calculates 50-period and 200-period moving averages, and generates buy/sell signals based on the Moving Averages Crossover strategy.
- The strategy only executes trades within the trading hours (9:15 AM to 3:30 PM).
Buy and Sell Execution:
- If a buy signal is generated and there is no existing position (
position == 0
), the strategy executes a market buy order for the NIFTY 50 index. - If a sell signal is generated and there is an existing long position (
position == 1
), the strategy executes a market sell order for the NIFTY 50 index.
Stop Loss and Target Execution:
- If there is an open long position (
position == 1
), the strategy monitors for stop-loss and target conditions. - The stop-loss price is calculated based on the
stop_loss_pct
percentage below the entry price, and the target price is calculated based on thetarget_pct
percentage above the entry price. - If the lowest price (
low
) reaches or goes below the stop-loss price, the strategy executes a market sell order to exit the position. - If the highest price (
high
) reaches or goes above the target price, the strategy executes a market sell order to exit the position.
Sleep Between Iterations:
- Error Handling:
- The code includes a try-except block to catch any exceptions that may occur during execution.
- End of Strategy:
- The strategy will continue running in a continuous loop until manually stopped.
- When you stop the script manually, it will print “Trading strategy stopped.”
Please note that this is a basic example for educational purposes only. Trading in financial markets involves risks, and using an automated strategy like this without proper risk management and testing can result in significant losses. Always thoroughly test your trading strategy in a demo or sandbox environment before using it in live trading and consider implementing stop-loss orders and other risk management techniques to protect your capital.