| name | trading-expert |
| version | 1.0.0 |
| description | Expert-level algorithmic trading, market systems, quantitative analysis, and trading platforms |
| category | domains |
| tags | ["trading","algorithmic-trading","quant","markets","finance","hft"] |
| allowed-tools | ["Read","Write","Edit","Bash(python:*)"] |
Trading Expert
Expert guidance for algorithmic trading systems, quantitative analysis, market data processing, and trading platform development.
Core Concepts
Trading Systems
- Algorithmic trading strategies
- High-frequency trading (HFT)
- Market making
- Arbitrage strategies
- Portfolio optimization
- Risk management
Market Data
- Order book processing
- Tick data analysis
- Market microstructure
- Real-time data feeds
- Historical data analysis
Execution
- Order routing
- Smart order routing (SOR)
- Execution algorithms (TWAP, VWAP)
- Slippage minimization
- Transaction cost analysis
Trading Strategy Implementation
import pandas as pd
import numpy as np
from typing import Optional
class TradingStrategy:
def __init__(self, symbol: str, capital: float = 100000):
self.symbol = symbol
self.capital = capital
self.position = 0
self.cash = capital
self.trades = []
def moving_average_crossover(self, data: pd.DataFrame,
short_window: int = 50,
long_window: int = 200) -> pd.Series:
"""Simple Moving Average Crossover Strategy"""
data['SMA_short'] = data['close'].rolling(window=short_window).mean()
data['SMA_long'] = data['close'].rolling(window=long_window).mean()
data['signal'] = 0
data.loc[data['SMA_short'] > data['SMA_long'], 'signal'] = 1
data.loc[data['SMA_short'] < data['SMA_long'], 'signal'] = -1
return data['signal']
() -> pd.Series:
data[] = data[].rolling(window=window).mean()
data[] = data[].rolling(window=window).std()
data[] = data[] + (data[] * num_std)
data[] = data[] - (data[] * num_std)
data[] =
data.loc[data[] < data[], ] =
data.loc[data[] > data[], ] = -
data[]
() -> pd.Series:
delta = data[].diff()
gain = (delta.where(delta > , )).rolling(window=period).mean()
loss = (-delta.where(delta < , )).rolling(window=period).mean()
rs = gain / loss
data[] = - ( / ( + rs))
data[] =
data.loc[data[] < , ] =
data.loc[data[] > , ] = -
data[]
:
():
.initial_capital = initial_capital
.capital = initial_capital
.position =
.trades = []
() -> :
portfolio_value = []
i ((data)):
signals.iloc[i] == .position == :
shares = .capital // data[].iloc[i]
cost = shares * data[].iloc[i]
.capital -= cost
.position = shares
.trades.append({
: ,
: data[].iloc[i],
: shares,
: data.index[i]
})
signals.iloc[i] == - .position > :
proceeds = .position * data[].iloc[i]
.capital += proceeds
.trades.append({
: ,
: data[].iloc[i],
: .position,
: data.index[i]
})
.position =
current_value = .capital + (.position * data[].iloc[i])
portfolio_value.append(current_value)
.calculate_metrics(portfolio_value, data)
() -> :
returns = pd.Series(portfolio_value).pct_change()
total_return = (portfolio_value[-] - .initial_capital) / .initial_capital
sharpe_ratio = returns.mean() / returns.std() * np.sqrt()
max_drawdown = .calculate_max_drawdown(portfolio_value)
{
: total_return,
: sharpe_ratio,
: max_drawdown,
: (.trades),
: portfolio_value[-]
}
() -> :
peak = portfolio_value[]
max_dd =
value portfolio_value:
value > peak:
peak = value
dd = (peak - value) / peak
dd > max_dd:
max_dd = dd
max_dd
Order Execution
from enum import Enum
from decimal import Decimal
from datetime import datetime
class OrderSide(Enum):
BUY = "BUY"
SELL = "SELL"
class OrderType(Enum):
MARKET = "MARKET"
LIMIT = "LIMIT"
STOP = "STOP"
STOP_LIMIT = "STOP_LIMIT"
class Order:
def __init__(self, symbol: str, side: OrderSide, order_type: OrderType,
quantity: int, price: Optional[Decimal] = None):
self.id = self.generate_order_id()
self.symbol = symbol
self.side = side
self.type = order_type
self.quantity = quantity
self.price = price
self.filled_quantity = 0
self.status = "NEW"
self.created_at = datetime.now()
def generate_order_id(self) -> str:
import uuid
return (uuid.uuid4())
:
():
.orders = {}
.positions = {}
() -> :
.orders[order.] = order
.route_order(order)
order.
() -> :
order_id .orders:
order = .orders[order_id]
order.status [, ]:
order.status =
():
venues = .get_venue_quotes(order.symbol)
best_venue = .select_best_venue(venues, order)
.send_to_venue(order, best_venue)
Risk Management
class RiskManager:
def __init__(self, max_position_size: float = 0.1,
max_portfolio_risk: float = 0.02,
stop_loss_pct: float = 0.05):
self.max_position_size = max_position_size
self.max_portfolio_risk = max_portfolio_risk
self.stop_loss_pct = stop_loss_pct
def calculate_position_size(self, capital: float, price: float,
volatility: float) -> int:
"""Calculate optimal position size using Kelly Criterion"""
max_position_value = capital * self.max_position_size
shares = int(max_position_value / price)
risk_adjusted_shares = int(shares * (1 - volatility))
return max(0, risk_adjusted_shares)
def check_risk_limits(self, portfolio: dict) -> bool:
"""Check if portfolio is within risk limits"""
total_value = portfolio['cash'] + sum(p['value'] for p in portfolio['positions'])
total_risk = sum(p['risk'] p portfolio[])
total_risk / total_value > .max_portfolio_risk:
() -> :
returns.quantile( - confidence)
Market Data Processing
class MarketDataProcessor:
def __init__(self):
self.order_book = {'bids': [], 'asks': []}
def process_tick(self, tick: dict):
"""Process real-time tick data"""
if tick['type'] == 'trade':
self.process_trade(tick)
elif tick['type'] == 'quote':
self.update_order_book(tick)
def update_order_book(self, quote: dict):
"""Update order book with new quote"""
if quote['side'] == 'bid':
self.order_book['bids'] = sorted(
self.order_book['bids'] + [(quote['price'], quote['size'])],
key=lambda x: x[0],
reverse=True
)[:100]
else:
self.order_book['asks'] = sorted(
self.order_book['asks'] + [(quote['price'], quote[])],
key= x: x[]
)[:]
() -> :
total_volume = (t[] t trades)
vwap = (t[] * t[] t trades) / total_volume
vwap
() -> :
.order_book[] .order_book[]:
best_bid = .order_book[][][]
best_ask = .order_book[][][]
best_ask - best_bid
Best Practices
- Always backtest strategies on historical data
- Implement proper risk management
- Monitor execution quality (slippage, fill rates)
- Use limit orders to control execution price
- Implement circuit breakers for risk control
- Log all trades and orders for audit
- Test in paper trading before live deployment
- Monitor latency in real-time systems
- Implement failover mechanisms
- Regular strategy performance review
Anti-Patterns
❌ No backtesting before live trading
❌ Ignoring transaction costs
❌ Over-optimization (curve fitting)
❌ No risk management
❌ Trading without stop losses
❌ Ignoring market microstructure
❌ No position sizing strategy
Resources