명시
"""
Fast Multi-Pair RSI Trading Bot
Supports:
- BTCUSDT
- XAUUSD
- GBPUSD
Opens fast buy or sell trades based on RSI signals
Closes trades after 5, 10, or 15 minutes
"""
import asyncio
import time
from dataclasses import dataclass, field
from typing import Dict, List, Optional
import pandas as pd
import numpy as np
# ===== RSI calculation ===== #
def compute_rsi(close: pd.Series, period: int = 14) -> pd.Series:
delta = close.diff()
gain = delta.clip(lower=0)
loss = -delta.clip(upper=0)
avg_gain = gain.ewm(alpha=1 / period, adjust=False).mean()
avg_loss = loss.ewm(alpha=1 / period, adjust=False).mean()
rs = avg_gain / avg_loss
return 100 - (100 / (1 + rs))
# ===== Position structure ===== #
@dataclass
class Position:
id: str
symbol: str
side: str
entry_price: float
size: float
opened_at: float
duration_min: int
# ===== Config ===== #
@dataclass
class BotConfig:
symbols: List[str] = field(default_factory=lambda: ["BTCUSDT", "XAUUSD", "GBPUSD"])
rsi_period: int = 14
rsi_oversold: int = 30
rsi_overbought: int = 70
durations_min: List[int] = field(default_factory=lambda: [5, 10, 15])
account_equity: float = 2000.0
risk_pct: float = 0.5
lot_size: Optional[float] = None
paper: bool = True
# ===== Trading Bot ===== #
class MultiPairRSIBot:
def __init__(self, cfg: BotConfig):
self.cfg = cfg
self.data: Dict[str, pd.DataFrame] = {sym: pd.DataFrame() for sym in cfg.symbols}
self.positions: Dict[str, Dict[str, Position]] = {sym: {} for sym in cfg.symbols}
self._id = 0
# ========== Fake 1-minute feed for PAPER mode ========== #
def get_fake_ohlcv(self, symbol):
now = int(time.time()) * 1000
df = self.data[symbol]
last_close = df["close"].iloc[-1] if not df.empty else 1000 + np.random.rand() * 10
change = np.random.normal(0, 0.0008)
close = last_close * (1 + change)
high = max(last_close, close)
low = min(last_close, close)
return (now, last_close, high, low, close, 0)
# ========== Append new candle ========== #
def append_candle(self, symbol, ohlc):
ts, o, h, l, c, v = ohlc
row = {"timestamp": pd.to_datetime(ts, unit="ms"),
"open": o, "high": h, "low": l, "close": c, "volume": v}
self.data[symbol] = pd.concat([self.data[symbol], pd.DataFrame([row])], ignore_index=True)
if len(self.data[symbol]) > 2000:
self.data[symbol] = self.data[symbol].iloc[-2000:]
# ========== Timeframe aggregation ========== #
def to_tf(self, symbol, minutes):
df = self.data[symbol]
if df.empty:
return pd.DataFrame()
df["bucket"] = df["timestamp"].dt.floor(f"{minutes}T")
out = df.groupby("bucket").agg({
"open": "first",
"high": "max",
"low": "min",
"close": "last",
"volume": "sum"
}).reset_index().rename(columns={"bucket": "timestamp"})
return out
# ========== Position sizing ========== #
def get_size(self, price):
if self.cfg.lot_size:
return self.cfg.lot_size
risk_amount = self.cfg.account_equity * (self.cfg.risk_pct / 100)
return round(risk_amount / price, 4)
# ========== Check RSI signals and enter trades ========== #
async def process_signals(self, symbol):
for dur in self.cfg.durations_min:
df = self.to_tf(symbol, dur)
if len(df) < self.cfg.rsi_period + 2:
continue
df["rsi"] = compute_rsi(df["close"], self.cfg.rsi_period)
prev = df["rsi"].iloc[-2]
last = df["rsi"].iloc[-1]
price = df["close"].iloc[-1]
# BUY: RSI cross up
if prev <= self.cfg.rsi_oversold and last > prev:
size = self.get_size(price)
await self.open_position(symbol, "buy", price, size, dur)
# SELL: RSI cross down
if prev >= self.cfg.rsi_overbought and last < prev:
size = self.get_size(price)
await self.open_position(symbol, "sell", price, size, dur)
# ========== Open position ========== #
async def open_position(self, symbol, side, price, size, duration):
self._id += 1
pid = f"{symbol}_{self._id}"
print(f"[{symbol}] OPEN {side.upper()} @ {price:.2f} | {duration}m | size {size}")
pos = Position(
id=pid,
symbol=symbol,
side=side,
entry_price=price,
size=size,
opened_at=time.time(),
duration_min=duration
)
self.positions[symbol][pid] = pos
# ========== Close expired trades ========== #
async def close_expired(self, symbol):
now = time.time()
to_close = []
for pid, pos in self.positions[symbol].items():
if (now - pos.opened_at) / 60 >= pos.duration_min:
to_close.append(pid)
for pid in to_close:
await self.close_position(symbol, pid)
# ========== Close position ========== #
async def close_position(self, symbol, pid):
pos = self.positions[symbol][pid]
last_price = self.data[symbol]["close"].iloc[-1]
pnl = (last_price - pos.entry_price) * pos.size if pos.side == "buy" else (pos.entry_price - last_price) * pos.size
print(f"[{symbol}] CLOSE {pos.side.upper()} @ {last_price:.2f} | PnL = {pnl:.3f}")
self.cfg.account_equity += pnl
del self.positions[symbol][pid]
# ========== Main loop ========== #
async def start(self):
print("Starting multi-pair RSI bot...")
print("Symbols:", self.cfg.symbols)
while True:
try:
for symbol in self.cfg.symbols:
# new candle
ohlcv = self.get_fake_ohlcv(symbol)
self.append_candle(symbol, ohlcv)
# signal scan
await self.process_signals(symbol)
# manage trades
await self.close_expired(symbol)
except Exception as e:
print("Error:", e)
await asyncio.sleep(1)
# ========== Launch Example ========== #
async def main():
cfg = BotConfig(
symbols=["BTCUSDT", "XAUUSD", "GBPUSD"],
account_equity=3000.0,
paper=True,
lot_size=None
)
bot = MultiPairRSIBot(cfg)
task = asyncio.create_task(bot.start())
await asyncio.sleep(60 * 5) # run 5 minutes demo
task.cancel()
if __name__ == "__main__":
asyncio.run(main())
응답함
1
등급
프로젝트
971
46%
중재
32
38%
/
34%
기한 초과
96
10%
작업중
게재됨: 6 코드
2
등급
프로젝트
17
12%
중재
3
0%
/
67%
기한 초과
1
6%
로드됨
3
등급
프로젝트
24
4%
중재
11
9%
/
73%
기한 초과
0
로드됨
4
등급
프로젝트
4
0%
중재
2
50%
/
50%
기한 초과
2
50%
무료
5
등급
프로젝트
11
0%
중재
5
40%
/
60%
기한 초과
2
18%
무료
6
등급
프로젝트
34
24%
중재
4
0%
/
50%
기한 초과
2
6%
작업중
7
등급
프로젝트
2
0%
중재
1
0%
/
0%
기한 초과
0
작업중
8
등급
프로젝트
2
0%
중재
0
기한 초과
0
무료
9
등급
프로젝트
15
7%
중재
8
38%
/
38%
기한 초과
2
13%
로드됨
10
등급
프로젝트
617
33%
중재
35
37%
/
49%
기한 초과
10
2%
로드됨
11
등급
프로젝트
6
0%
중재
3
0%
/
33%
기한 초과
3
50%
로드됨
12
등급
프로젝트
2
0%
중재
0
기한 초과
0
무료
13
등급
프로젝트
3320
67%
중재
77
48%
/
14%
기한 초과
342
10%
무료
게재됨: 1 코드
14
등급
프로젝트
3
0%
중재
0
기한 초과
0
무료
15
등급
프로젝트
0
0%
중재
0
기한 초과
0
무료
16
등급
프로젝트
1
100%
중재
0
기한 초과
0
무료
17
등급
프로젝트
253
30%
중재
0
기한 초과
3
1%
무료
게재됨: 2 코드
18
등급
프로젝트
28
18%
중재
20
10%
/
50%
기한 초과
8
29%
작업중
19
등급
프로젝트
1
0%
중재
0
기한 초과
0
무료
20
등급
프로젝트
467
39%
중재
101
41%
/
23%
기한 초과
75
16%
바쁜
게재됨: 2 코드
21
등급
프로젝트
0
0%
중재
0
기한 초과
0
무료
22
등급
프로젝트
0
0%
중재
0
기한 초과
0
무료
23
등급
프로젝트
0
0%
중재
0
기한 초과
0
무료
비슷한 주문
CREATE AN EA
30 - 50 USD
ON A XAUUSD 15 MIN CHART PLACE SELL ORDER WHEN EMA 100 IS 500 PIPS ABOVE CURRENT PRICE & BUY ORDER WHEN EMA 100 IS 500 PIPS BELOW WITH TP 50 PIPS SL 50 PIPS with trailing stop to start after 40 pips profit and trails by 30 pips thereafter, SESSION LONDON SESSION OVERLAPPING WITH NY SESSION
Tradingview Strategy To Ninjatrder 8
80 - 100 USD
Hello, i have a strategy from my tradingview indicator that i would like to turn into a ninjatrader automated trading bot. i would like to include a expire date that i can adjust monthly for my clients. i want it to work with unirenko candles and have a trailing stoploss and breakeven, with take profit 1 & Take profit 2 i want this to work with unirenko and also have an Expire date that only i can control i also want
I already have 4 different indicators on tradingview source codes I wanted to merge 2 then 2 the way the are without changing the source codes or the original source. Each drawings and signals should remains same even after merging 2 and 2 separately by making it 2 indicators instead of 4 as they are now. You will make it compatible with tradingview panel without changing the original source of each.I want it within
Subject: Request for Expert MT5 Forex EA Developer Hello, I am looking for a professional MetaTrader 5 Forex Expert Advisor (EA) developer with extensive experience. I want a fast AI-powered trading bot for MT5 that can: Open multiple trades automatically, whether buy or sell, and close them for profit. Execute high-frequency scalping with high precision. Analyze or predict the market trend (buy or sell) and act
Job Title: Cloud-Based MT4/MT5 Trade Copier Developer (Project-Based) Project Overview: Looking for an experienced developer to build a cloud-hosted trade copier platform similar in concept to leading web-based multi-account trade copiers. The system must copy trades in real time between multiple MT4/MT5 accounts (and later other platforms), with low latency, strong security, and a modern web dashboard for
I want the Robots to execute buy/sell/TP/SL trades without me telling them to, Buy low Sell high Forex Pairs, I want to gain profit not lose profit, using INDICATORS, strategies, Expert Advisors, signals, Symbols, MA RSI, Awesome Accelerators', Algorithmic Trading and Scanners on real time data
I am looking for a professional MT5 developer to build an institutional-grade Expert Advisor for XAUUSD using a hybrid system of Artificial Intelligence and Smart Money Concepts (SMC). The EA must use AI for direction, SL/TP prediction, volatility analysis, and market regime detection, while SMC handles structure-based entries (OB, FVG, liquidity). Trading must be one-shot only, with strong risk management, no
NinjaTrader
100 - 150 USD
Hey, I’m looking to do the following and was wondering if you can help: I want clients to securely connect their trading accounts to our dashboard so they can see everything in real time: PnL, balance, open positions, trade history, and performance metrics. The client experience should be extremely simple: they log in, connect their account through a secure authentication flow, and then manage everything from our
Mt5 mobile with delayed charts ios
100+ USD
Looking for a developer to make mobile MT5 with delayed charts can choose the day and will work exactly like normal metatrader, even lot size the profit and losses and everything can add capital etc
have an MT5 Expert Advisor (EA) that requires professional attention. The tasks are: 1. Debug the EA and fix any errors. 2. Optimize the EA input parameters for best performance. 3. Run strategy tests and provide a detailed report including: - Profit - Drawdown - Trade log - Recommendations Requirements: - Experience with MT5 EA debugging, optimization, and backtesting. - Able to deliver updated .mq5/.ex5
프로젝트 정보
예산
50+ USD
고객
넣은 주문1
중재 수0