OPEN-SOURCE SCRIPT

My strategy

import pandas as pd
import ta
import time
from dhan import DhanHQ

# Dhan API Credentials
API_KEY = "your_api_key"
ACCESS_TOKEN = "your_access_token"
dhan = DhanHQ(api_key=API_KEY, access_token=ACCESS_TOKEN)

# Strategy Parameters
SYMBOL = "RELIANCE" # Replace with your stock symbol
INTERVAL = "1min" # Scalping requires a short timeframe
STOPLOSS_PERCENT = 0.2 # Stop loss percentage (0.2% per trade)
TARGET_RR_RATIO = 2 # Risk-Reward Ratio (1:2)
QUANTITY = 10 # Number of shares per trade

def get_historical_data(symbol, interval="1min", limit=50):
"""Fetch historical data from Dhan API."""
response = dhan.get_historical_data(symbol=symbol, interval=interval, limit=limit)

if response["status"] == "success":
df = pd.DataFrame(response["data"])
df["close"] = df["close"].astype(float)
df["high"] = df["high"].astype(float)
df["low"] = df["low"].astype(float)
df["open"] = df["open"].astype(float)
return df
else:
raise Exception("Failed to fetch data: ", response["message"])

def add_indicators(df):
"""Calculate EMA (9 & 20), VWAP, and RSI."""
df["EMA_9"] = ta.trend.ema_indicator(df["close"], window=9)
df["EMA_20"] = ta.trend.ema_indicator(df["close"], window=20)
df["VWAP"] = ta.volume.volume_weighted_average_price(df["high"], df["low"], df["close"], df["volume"])
df["RSI"] = ta.momentum.rsi(df["close"], window=14)
return df

def check_signals(df):
"""Identify Buy and Sell signals based on EMA, VWAP, and RSI."""
latest = df.iloc[-1]

# Buy Condition
if latest["EMA_9"] > latest["EMA_20"] and latest["close"] > latest["VWAP"] and 40 <= latest["RSI"] <= 60:
return "BUY"

# Sell Condition
if latest["EMA_9"] < latest["EMA_20"] and latest["close"] < latest["VWAP"] and 40 <= latest["RSI"] <= 60:
return "SELL"

return None

def place_order(symbol, side, quantity):
"""Execute a market order."""
order_type = "BUY" if side == "BUY" else "SELL"
order = dhan.place_order(symbol=symbol, order_type="MARKET", quantity=quantity, transaction_type=order_type)

if order["status"] == "success":
print(f"{order_type} Order Placed: {order['data']['price']}")
return float(order["data"]["price"]) # Return entry price
else:
raise Exception("Order Failed: ", order["message"])

def scalping_strategy():
position = None
entry_price = 0
stoploss = 0
target = 0

while True:
try:
# Fetch and process data
df = get_historical_data(SYMBOL, INTERVAL)
df = add_indicators(df)
signal = check_signals(df)

# Execute trade
if signal == "BUY" and position is None:
entry_price = place_order(SYMBOL, "BUY", QUANTITY)
stoploss = entry_price * (1 - STOPLOSS_PERCENT / 100)
target = entry_price + (entry_price - stoploss) * TARGET_RR_RATIO
position = "LONG"
print(f"BUY @ {entry_price}, SL: {stoploss}, Target: {target}")

elif signal == "SELL" and position is None:
entry_price = place_order(SYMBOL, "SELL", QUANTITY)
stoploss = entry_price * (1 + STOPLOSS_PERCENT / 100)
target = entry_price - (stoploss - entry_price) * TARGET_RR_RATIO
position = "SHORT"
print(f"SELL @ {entry_price}, SL: {stoploss}, Target: {target}")

# Exit logic
if position:
current_price = df["close"].iloc[-1]
if (position == "LONG" and (current_price <= stoploss or current_price >= target)) or \
(position == "SHORT" and (current_price >= stoploss or current_price <= target)):
print(f"Exiting {position} @ {current_price}")
position = None

time.sleep(60) # Wait for the next candle

except Exception as e:
print(f"Error: {e}")
time.sleep(60)

# Run the strategy
try:
scalping_strategy()
except KeyboardInterrupt:
print("Trading stopped manually.")

免責聲明