-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrader.py
More file actions
156 lines (130 loc) · 5.87 KB
/
Trader.py
File metadata and controls
156 lines (130 loc) · 5.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
import ccxt
import time
import numpy as np
import pandas as pd
import tensorflow as tf # Assuming you are using TensorFlow for the CNN model
from sqlite3 import connect
from sklearn.preprocessing import StandardScaler
# Set up the Binance client
api_key = 'YOUR_API_KEY'
api_secret = 'YOUR_API_SECRET'
exchange = ccxt.binance({
'apiKey': api_key,
'secret': api_secret,
'enableRateLimit': True,
'options': {'defaultType': 'future'} # for futures trading
})
# Define the trading symbols
symbols = ['BTC/USDT', 'ETH/USDT', 'BNB/USDT', 'SOL/USDT', 'XRP/USDT']
# CNN Model Path (assuming pre-trained model)
model_path = 'path_to_your_trained_cnn_model.h5'
cnn_model = tf.keras.models.load_model(model_path)
# Initialize the scaler for normalization
scaler = StandardScaler()
# Database for storing trades
db = connect('trades.db')
cursor = db.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS trades (symbol TEXT, order_id TEXT, type TEXT, price REAL, amount REAL, status TEXT)''')
# Function to fetch OHLCV data and compute technical indicators (with rate-limiting)
def fetch_data(symbol, timeframe='1h', limit=100):
try:
# Fetch OHLCV data from Binance
ohlcv = exchange.fetch_ohlcv(symbol, timeframe, limit=limit)
df = pd.DataFrame(ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
# Compute technical indicators
df['rsi'] = compute_rsi(df['close'])
df['adx'] = compute_adx(df)
df['atr'] = compute_atr(df)
df['vwap'] = compute_vwap(df)
df['taker_ratio'] = compute_taker_ratio(df) # Custom function to calculate Taker Ratio
return df
except Exception as e:
print(f"Error fetching data for {symbol}: {str(e)}")
return None
# Compute RSI
def compute_rsi(data, period=14):
delta = data.diff()
gain = delta.where(delta > 0, 0)
loss = -delta.where(delta < 0, 0)
avg_gain = gain.rolling(window=period).mean()
avg_loss = loss.rolling(window=period).mean()
rs = avg_gain / avg_loss
return 100 - (100 / (1 + rs))
# Compute ADX
def compute_adx(df, period=14):
high = df['high']
low = df['low']
close = df['close']
tr = np.maximum(high - low, np.abs(high - close.shift(1)), np.abs(low - close.shift(1)))
atr = tr.rolling(window=period).mean()
return atr
# Compute ATR
def compute_atr(df, period=14):
df['tr'] = np.maximum(df['high'] - df['low'], np.abs(df['high'] - df['close'].shift(1)), np.abs(df['low'] - df['close'].shift(1)))
return df['tr'].rolling(window=period).mean()
# Compute VWAP
def compute_vwap(df):
df['vwap'] = (df['volume'] * df['close']).cumsum() / df['volume'].cumsum()
return df['vwap']
# Compute Taker Ratio (Custom Indicator)
def compute_taker_ratio(df):
return df['volume'] / df['volume'].mean()
# Preprocess the data for CNN
def preprocess_data(df):
features = df[['rsi', 'adx', 'atr', 'vwap', 'taker_ratio']].values[-20:]
return scaler.fit_transform(features)
# Make Prediction using the CNN model
def predict_price_move(preprocessed_data):
prediction = cnn_model.predict(np.expand_dims(preprocessed_data, axis=0))
return prediction[0] # Assume model returns a probability or regression output
# Place an order on Binance
def place_order(symbol, side, amount, price):
if side == 'buy':
order = exchange.create_market_buy_order(symbol, amount)
elif side == 'sell':
order = exchange.create_market_sell_order(symbol, amount)
return order
# Risk management using SMC concepts for SL and ATR for TP
def calculate_smc_stop_loss(df, entry_price):
# For simplicity, assume we use a basic market structure (HH/HL or LH/LL) to determine the stop loss
# Example SMC-based: Stop below the last swing low if uptrend (HH/HL)
last_low = df['low'].min() # Example of low for simplicity
return last_low * 0.99 # Stop-loss 1% below the last swing low
def calculate_atr_take_profit(df, entry_price):
atr = df['atr'].iloc[-1] # Most recent ATR value
return entry_price + 2 * atr # TP at 2x ATR above entry price
# Trade Management Loop
def trading_loop():
for symbol in symbols:
df = fetch_data(symbol)
if df is None:
continue
preprocessed_data = preprocess_data(df)
prediction = predict_price_move(preprocessed_data)
# Check if the CNN model predicts a significant move (example threshold)
if prediction > 0.5: # If the probability of a price move exceeds 50%
entry_price = df['close'].iloc[-1]
stop_loss = calculate_smc_stop_loss(df, entry_price)
take_profit = calculate_atr_take_profit(df, entry_price)
# Place a buy order (for simplicity, you could add a more complex strategy here)
order = place_order(symbol, 'buy', 0.01, entry_price) # Example: 0.01 BTC
print(f"Placed buy order for {symbol} at {entry_price}.")
# Risk management: Monitor stop-loss and take-profit
while True:
df = fetch_data(symbol)
current_price = df['close'].iloc[-1]
# Check if the price hits the stop-loss or take-profit
if current_price <= stop_loss:
place_order(symbol, 'sell', 0.01, current_price)
print(f"Sell order triggered for {symbol} at {current_price}. Stop-loss hit.")
break
elif current_price >= take_profit:
place_order(symbol, 'sell', 0.01, current_price)
print(f"Sell order triggered for {symbol} at {current_price}. Take-profit hit.")
break
time.sleep(60) # Wait a minute before checking again
time.sleep(60) # Sleep for a minute before checking the next symbol
# Main execution
if __name__ == '__main__':
trading_loop()