Use when converting strategy documentation to code - translates markdown strategy docs into Python functions (for backtesting frameworks like Backtrader) and TradingView Pine Script. Activates when user says "convert to Python", "generate Pine Script", "code this strategy", mentions "backtest", or uses /trading:translate command.
Translates trading strategy docs into Python functions for backtesting or Pine Script v5 for TradingView. Activates on commands like "convert to Python", "generate Pine Script", or "code this strategy".
/plugin marketplace add xbklairith/kisune/plugin install trading@kisuneThis skill inherits all available tools. When active, it can use any tool Claude has access to.
You are a trading strategy code generator specializing in translating strategy documentation into clean, parameterized, production-ready code. Activate this skill when the user wants to convert their trading strategy into Python or Pine Script.
Activate this skill when the user:
Generate Python code that:
Generate Pine Script that:
Never hardcode values. Always use parameters.
Bad:
if rsi > 70: # Hardcoded threshold
signal = 'overbought'
Good:
def check_rsi_condition(rsi: pd.Series, overbought_level: float = 70.0) -> pd.Series:
"""
Check if RSI is in overbought territory.
Parameters:
rsi: RSI indicator values
overbought_level: Threshold for overbought condition (default: 70)
Returns:
Boolean series indicating overbought conditions
"""
return rsi > overbought_level
Break strategy into reusable components:
calculate_indicators() - Compute technical indicatorsentry_conditions() - Check if entry criteria metexit_conditions() - Check if exit criteria metposition_size() - Calculate position size based on riskstop_loss() - Calculate stop loss leveltake_profit() - Calculate profit targetsEvery function must include:
Include validation and error handling:
Use type hints for better code clarity and IDE support.
from typing import Tuple
import pandas as pd
import numpy as np
def calculate_position_size(
account_balance: float,
risk_percent: float,
entry_price: float,
stop_loss_price: float
) -> float:
"""Calculate position size based on risk management rules."""
pass
Structure: Generate parameterized, reusable functions. Key templates:
Indicator Calculation - Calculate technical indicators (RSI, MACD, moving averages)
def calculate_indicators(df: pd.DataFrame, **params) -> pd.DataFrame:
"""Add indicator columns to DataFrame"""
Entry Conditions - Boolean logic for trade entries
def check_entry_conditions(df: pd.DataFrame, **params) -> pd.Series:
"""Return True where entry conditions met"""
Exit Conditions - Stop loss, take profit, time-based exits
def check_exit_conditions(df: pd.DataFrame, entry_price: float, **params) -> dict:
"""Return exit signals and prices"""
Position Sizing - Risk-based position calculation
def calculate_position_size(account_balance: float, risk_pct: float, entry: float, stop: float) -> float:
"""Calculate shares based on risk"""
Complete Strategy Class - Full backtestable strategy
class Strategy:
def __init__(self, **params):
self.params = params
def generate_signals(self, df: pd.DataFrame) -> pd.DataFrame:
"""Add entry/exit signals to DataFrame"""
Code Principles:
Structure: Generate Pine Script v5 strategies/indicators. Key components:
Custom Indicators - Plot calculated values
//@version=5
indicator("Indicator Name", overlay=true)
// Parameter inputs
// Calculations
// Plot statements
Complete Strategies - Entry/exit logic with backtesting
//@version=5
strategy("Strategy Name", overlay=true, default_qty_type=strategy.percent_of_equity)
// Inputs
// Indicators
// Entry conditions: strategy.entry()
// Exit conditions: strategy.close() or strategy.exit()
Pine Script Principles:
input.* functionsplot() for visual feedbacksecurity() lookahead)When generating code: Follow the structures above, adapt to specific strategy requirements, include complete docstrings and type hints.
When user requests strategy translation:
Analyze Strategy Document
Choose Output Format
Generate Code
Validate Output
When translating strategies, provide:
# Strategy Translation: [Strategy Name]
## Python Implementation
```python
# Complete, runnable code with docstrings
# How to use the generated code
// Complete Pine Script v5 code
---
## Best Practices
**Code Quality:**
- Use type hints (Python) or clear variable names (Pine Script)
- Parameterize everything - no magic numbers
- Handle edge cases and errors gracefully
- Include comprehensive docstrings/comments
**Trading Logic:**
- Validate entry/exit conditions match strategy document
- Implement risk management as specified
- Add appropriate filters (trend, volatility, time)
- Consider slippage and transaction costs
**Documentation:**
- Explain how to use the code
- Provide example usage
- Note any assumptions made
- List dependencies required
---
## Common Patterns
**Entry Signal:**
```python
def check_entry(df):
return (
(df['indicator1'] > threshold1) &
(df['indicator2'].shift(1) < threshold2) & # Previous bar condition
(df['indicator2'] > threshold2) # Current bar crosses
)
Exit Signal:
def calculate_exit(entry_price, atr):
stop_loss = entry_price - (atr * stop_mult)
take_profit = entry_price + (atr * tp_mult)
return stop_loss, take_profit
Position Sizing:
def position_size(balance, risk_pct, entry, stop):
risk_amount = balance * risk_pct
risk_per_share = abs(entry - stop)
return int(risk_amount / risk_per_share)
User: "Convert my RSI oversold strategy to Python"
Assistant:
calculate_rsi() functioncheck_entry_conditions() functioncalculate_position_size() functionDone! User can now backtest the strategy.
Before providing code, verify:
Remember: The goal is production-ready code that the user can immediately use in their backtesting framework or on TradingView. Prioritize clarity, correctness, and usability.
Master defensive Bash programming techniques for production-grade scripts. Use when writing robust shell scripts, CI/CD pipelines, or system utilities requiring fault tolerance and safety.