mirror of
https://github.com/discountry/ritmex-bot.git
synced 2026-09-09 08:18:07 +00:00
Add swing trading strategy with RSI signals and Binance integration
- Introduced a new swing trading strategy utilizing the RSI indicator on the ETHBTC pair from Binance. - Implemented the `SwingEngine` to manage trading logic, including entry and exit conditions based on RSI thresholds. - Added configuration options for swing direction, trade amount, and RSI parameters in `config.ts`. - Created new documentation for the swing strategy, detailing its behavior and configuration. - Enhanced CLI to support the new swing strategy option. - Added tests for swing logic to ensure correct behavior under various market conditions.
This commit is contained in:
@@ -0,0 +1,369 @@
|
||||
- The following base endpoints are available. Please use whichever works best for your setup:
|
||||
- **[https://api.binance.com](https://api.binance.com/)**
|
||||
- **[https://api-gcp.binance.com](https://api-gcp.binance.com/)**
|
||||
- **[https://api1.binance.com](https://api1.binance.com/)**
|
||||
- **[https://api2.binance.com](https://api2.binance.com/)**
|
||||
- **[https://api3.binance.com](https://api3.binance.com/)**
|
||||
- **[https://api4.binance.com](https://api4.binance.com/)**
|
||||
- The last 4 endpoints in the point above (`api1` - `api4`) should give better performance but have less stability.
|
||||
- Responses are in JSON by default. To receive responses in SBE, refer to the [SBE FAQ](https://developers.binance.com/docs/binance-spot-api-docs/faqs/sbe_faq) page.
|
||||
- If your request contains a symbol name containing non-ASCII characters, then the response may contain non-ASCII characters encoded in UTF-8.
|
||||
- Some endpoints may return asset and/or symbol names containing non-ASCII characters encoded in UTF-8 even if the request did not contain non-ASCII characters.
|
||||
- Data is returned in **chronological order**, unless noted otherwise.
|
||||
- Without `startTime` or `endTime`, returns the most recent items up to the limit.
|
||||
- With `startTime`, returns oldest items from `startTime` up to the limit.
|
||||
- With `endTime`, returns most recent items up to `endTime` and the limit.
|
||||
- With both, behaves like `startTime` but does not exceed `endTime`.
|
||||
- All time and timestamp related fields in the JSON responses are in **milliseconds by default.** To receive the information in microseconds, please add the header `X-MBX-TIME-UNIT:MICROSECOND` or `X-MBX-TIME-UNIT:microsecond`.
|
||||
- We support HMAC, RSA, and Ed25519 keys. For more information, please see [API Key types](https://developers.binance.com/docs/binance-spot-api-docs/faqs/api_key_types).
|
||||
- Timestamp parameters (e.g. `startTime`, `endTime`, `timestamp`) can be passed in milliseconds or microseconds.
|
||||
- For APIs that only send public market data, please use the base endpoint **[https://data-api.binance.vision](https://data-api.binance.vision/)**. Please refer to [Market Data Only](https://developers.binance.com/docs/binance-spot-api-docs/faqs/market_data_only) page.
|
||||
- If there are enums or terms you want clarification on, please see the [SPOT Glossary](https://developers.binance.com/docs/binance-spot-api-docs/faqs/spot_glossary) for more information.
|
||||
- APIs have a timeout of 10 seconds when processing a request. If a response from the Matching Engine takes longer than this, the API responds with "Timeout waiting for response from backend server. Send status unknown; execution status unknown." [(-1007 TIMEOUT)](https://developers.binance.com/docs/binance-spot-api-docs/errors#-1007-timeout)
|
||||
- This does not always mean that the request failed in the Matching Engine.
|
||||
- If the status of the request has not appeared in [User Data Stream](https://developers.binance.com/docs/binance-spot-api-docs/user-data-stream), please perform an API query for its status.
|
||||
- **Please avoid SQL keywords in requests** as they may trigger a security block by a WAF (Web Application Firewall) rule. See [https://www.binance.com/en/support/faq/detail/360004492232](https://www.binance.com/en/support/faq/detail/360004492232) for more details.
|
||||
- If your request contains a symbol name containing non-ASCII characters, then the response may contain non-ASCII characters encoded in UTF-8.
|
||||
- Some endpoints may return asset and/or symbol names containing non-ASCII characters encoded in UTF-8 even if the request did not contain non-ASCII characters.
|
||||
|
||||
Kline/Candlestick data
|
||||
GET /api/v3/klines
|
||||
|
||||
Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time.
|
||||
|
||||
Weight: 2
|
||||
|
||||
Parameters:
|
||||
|
||||
Name Type Mandatory Description
|
||||
symbol STRING YES
|
||||
interval ENUM YES
|
||||
startTime LONG NO
|
||||
endTime LONG NO
|
||||
timeZone STRING NO Default: 0 (UTC)
|
||||
limit INT NO Default: 500; Maximum: 1000.
|
||||
Supported kline intervals (case-sensitive):
|
||||
|
||||
Interval interval value
|
||||
seconds 1s
|
||||
minutes 1m, 3m, 5m, 15m, 30m
|
||||
hours 1h, 2h, 4h, 6h, 8h, 12h
|
||||
days 1d, 3d
|
||||
weeks 1w
|
||||
months 1M
|
||||
Notes:
|
||||
|
||||
If startTime and endTime are not sent, the most recent klines are returned.
|
||||
Supported values for timeZone:
|
||||
Hours and minutes (e.g. -1:00, 05:45)
|
||||
Only hours (e.g. 0, 8, 4)
|
||||
Accepted range is strictly [-12:00 to +14:00] inclusive
|
||||
If timeZone provided, kline intervals are interpreted in that timezone instead of UTC.
|
||||
Note that startTime and endTime are always interpreted in UTC, regardless of timeZone.
|
||||
Data Source: Database
|
||||
|
||||
Response:
|
||||
|
||||
[
|
||||
[
|
||||
1499040000000, // Kline open time
|
||||
"0.01634790", // Open price
|
||||
"0.80000000", // High price
|
||||
"0.01575800", // Low price
|
||||
"0.01577100", // Close price
|
||||
"148976.11427815", // Volume
|
||||
1499644799999, // Kline Close time
|
||||
"2434.19055334", // Quote asset volume
|
||||
308, // Number of trades
|
||||
"1756.87402397", // Taker buy base asset volume
|
||||
"28.46694368", // Taker buy quote asset volume
|
||||
"0" // Unused field, ignore.
|
||||
]
|
||||
]
|
||||
|
||||
|
||||
## WebSocket Streams for Binance
|
||||
|
||||
## General WSS information
|
||||
|
||||
- The base endpoint is: **wss://stream.binance.com:9443** or **wss://stream.binance.com:443**.
|
||||
- Streams can be accessed either in a single raw stream or in a combined stream.
|
||||
- Raw streams are accessed at **/ws/<streamName>**
|
||||
- Combined streams are accessed at **/stream?streams=<streamName1>/<streamName2>/<streamName3>**
|
||||
- Combined stream events are wrapped as follows: **{"stream":"<streamName>","data":<rawPayload>}**
|
||||
- All symbols for streams are **lowercase**
|
||||
- A single connection to **stream.binance.com** is only valid for 24 hours; expect to be disconnected at the 24 hour mark
|
||||
- The WebSocket server will send a `ping frame` every 20 seconds.
|
||||
- If the WebSocket server does not receive a `pong frame` back from the connection within a minute the connection will be disconnected.
|
||||
- When you receive a ping, you must send a pong with a copy of ping's payload as soon as possible.
|
||||
- Unsolicited `pong frames` are allowed, but will not prevent disconnection. **It is recommended that the payload for these pong frames are empty.**
|
||||
- The base endpoint **wss://data-stream.binance.vision** can be subscribed to receive **only** market data messages.
|
||||
User data stream is **NOT** available from this URL.
|
||||
- All time and timestamp related fields are **milliseconds by default**. To receive the information in microseconds, please add the parameter `timeUnit=MICROSECOND or timeUnit=microsecond` in the URL.
|
||||
- For example: `/stream?streams=btcusdt@trade&timeUnit=MICROSECOND`
|
||||
- If your request contains a symbol name containing non-ASCII characters, then the stream events may contain non-ASCII characters encoded in UTF-8.
|
||||
- \[All Market Mini Tickers Stream\](#all-market-mini-tickers-stream and [All Market Rolling Window Statistics Streams](https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#all-market-rolling-window-statistics-streams) events may contain non-ASCII characters encoded in UTF-8.
|
||||
|
||||
## WebSocket Limits
|
||||
|
||||
- WebSocket connections have a limit of 5 incoming messages per second. A message is considered:
|
||||
- A PING frame
|
||||
- A PONG frame
|
||||
- A JSON controlled message (e.g. subscribe, unsubscribe)
|
||||
- A connection that goes beyond the limit will be disconnected; IPs that are repeatedly disconnected may be banned.
|
||||
- A single connection can listen to a maximum of 1024 streams.
|
||||
- There is a limit of **300 connections per attempt every 5 minutes per IP**.
|
||||
|
||||
## Live Subscribing/Unsubscribing to streams
|
||||
|
||||
- The following data can be sent through the WebSocket instance in order to subscribe/unsubscribe from streams. Examples can be seen below.
|
||||
- The `id` is used as an identifier to uniquely identify the messages going back and forth. The following formats are accepted:
|
||||
- 64-bit signed integer
|
||||
- alphanumeric strings; max length 36
|
||||
- `null`
|
||||
- In the response, if the `result` received is `null` this means the request sent was a success for non-query requests (e.g. Subscribing/Unsubscribing).
|
||||
|
||||
### Subscribe to a stream
|
||||
|
||||
- Request
|
||||
- Response
|
||||
```javascript
|
||||
{
|
||||
"result": null,
|
||||
"id": 1
|
||||
}
|
||||
```
|
||||
|
||||
### Unsubscribe to a stream
|
||||
|
||||
- Request
|
||||
- Response
|
||||
```javascript
|
||||
{
|
||||
"result": null,
|
||||
"id": 312
|
||||
}
|
||||
```
|
||||
|
||||
### Listing Subscriptions
|
||||
|
||||
- Request
|
||||
```javascript
|
||||
{
|
||||
"method": "LIST_SUBSCRIPTIONS",
|
||||
"id": 3
|
||||
}
|
||||
```
|
||||
- Response
|
||||
```javascript
|
||||
{
|
||||
"result": ["btcusdt@aggTrade"],
|
||||
"id": 3
|
||||
}
|
||||
```
|
||||
|
||||
### Setting Properties
|
||||
|
||||
Currently, the only property that can be set is whether `combined` stream payloads are enabled or not. The combined property is set to `false` when connecting using `/ws/` ("raw streams") and `true` when connecting using `/stream/`.
|
||||
|
||||
- Request
|
||||
```javascript
|
||||
{
|
||||
"method": "SET_PROPERTY",
|
||||
"params": ["combined", true],
|
||||
"id": 5
|
||||
}
|
||||
```
|
||||
- Response
|
||||
```javascript
|
||||
{
|
||||
"result": null,
|
||||
"id": 5
|
||||
}
|
||||
```
|
||||
|
||||
### Retrieving Properties
|
||||
|
||||
- Request
|
||||
```javascript
|
||||
{
|
||||
"method": "GET_PROPERTY",
|
||||
"params": ["combined"],
|
||||
"id": 2
|
||||
}
|
||||
```
|
||||
- Response
|
||||
```javascript
|
||||
{
|
||||
"result": true, // Indicates that combined is set to true.
|
||||
"id": 2
|
||||
}
|
||||
```
|
||||
|
||||
| Error Message | Description |
|
||||
| --- | --- |
|
||||
| {"code": 0, "msg": "Unknown property","id": %s} | Parameter used in the `SET_PROPERTY` or `GET_PROPERTY` was invalid |
|
||||
| {"code": 1, "msg": "Invalid value type: expected Boolean"} | Value should only be `true` or `false` |
|
||||
| {"code": 2, "msg": "Invalid request: property name must be a string"} | Property name provided was invalid |
|
||||
| {"code": 2, "msg": "Invalid request: request ID must be an unsigned integer"} | Parameter `id` had to be provided or the value provided in the `id` parameter is an unsupported type |
|
||||
| {"code": 2, "msg": "Invalid request: unknown variant %s, expected one of `SUBSCRIBE`, `UNSUBSCRIBE`, `LIST_SUBSCRIPTIONS`, `SET_PROPERTY`, `GET_PROPERTY` at line 1 column 28"} | Possible typo in the provided method or provided method was neither of the expected values |
|
||||
| {"code": 2, "msg": "Invalid request: too many parameters"} | Unnecessary parameters provided in the data |
|
||||
| {"code": 2, "msg": "Invalid request: property name must be a string"} | Property name was not provided |
|
||||
| {"code": 2, "msg": "Invalid request: missing field `method` at line 1 column 73"} | `method` was not provided in the data |
|
||||
| {"code":3,"msg":"Invalid JSON: expected value at line %s column %s"} | JSON data sent has incorrect syntax. |
|
||||
|
||||
## Detailed Stream information
|
||||
|
||||
## Aggregate Trade Streams
|
||||
|
||||
The Aggregate Trade Streams push trade information that is aggregated for a single taker order.
|
||||
|
||||
**Stream Name:** <symbol>@aggTrade
|
||||
|
||||
**Update Speed:** Real-time
|
||||
|
||||
**Payload:**
|
||||
|
||||
```javascript
|
||||
{
|
||||
"e": "aggTrade", // Event type
|
||||
"E": 1672515782136, // Event time
|
||||
"s": "BNBBTC", // Symbol
|
||||
"a": 12345, // Aggregate trade ID
|
||||
"p": "0.001", // Price
|
||||
"q": "100", // Quantity
|
||||
"f": 100, // First trade ID
|
||||
"l": 105, // Last trade ID
|
||||
"T": 1672515782136, // Trade time
|
||||
"m": true, // Is the buyer the market maker?
|
||||
"M": true // Ignore
|
||||
}
|
||||
```
|
||||
|
||||
## Trade Streams
|
||||
|
||||
The Trade Streams push raw trade information; each trade has a unique buyer and seller.
|
||||
|
||||
**Stream Name:** <symbol>@trade
|
||||
|
||||
**Update Speed:** Real-time
|
||||
|
||||
**Payload:**
|
||||
|
||||
```javascript
|
||||
{
|
||||
"e": "trade", // Event type
|
||||
"E": 1672515782136, // Event time
|
||||
"s": "BNBBTC", // Symbol
|
||||
"t": 12345, // Trade ID
|
||||
"p": "0.001", // Price
|
||||
"q": "100", // Quantity
|
||||
"T": 1672515782136, // Trade time
|
||||
"m": true, // Is the buyer the market maker?
|
||||
"M": true // Ignore
|
||||
}
|
||||
```
|
||||
|
||||
## Kline/Candlestick Streams for UTC
|
||||
|
||||
The Kline/Candlestick Stream push updates to the current klines/candlestick every second in `UTC+0` timezone
|
||||
|
||||
**Kline/Candlestick chart intervals:**
|
||||
|
||||
s-> seconds; m -> minutes; h -> hours; d -> days; w -> weeks; M -> months
|
||||
|
||||
- 1s
|
||||
- 1m
|
||||
- 3m
|
||||
- 5m
|
||||
- 15m
|
||||
- 30m
|
||||
- 1h
|
||||
- 2h
|
||||
- 4h
|
||||
- 6h
|
||||
- 8h
|
||||
- 12h
|
||||
- 1d
|
||||
- 3d
|
||||
- 1w
|
||||
- 1M
|
||||
|
||||
**Stream Name:** <symbol>@kline\_<interval>
|
||||
|
||||
**Update Speed:** 1000ms for `1s`, 2000ms for the other intervals
|
||||
|
||||
**Payload:**
|
||||
|
||||
```javascript
|
||||
{
|
||||
"e": "kline", // Event type
|
||||
"E": 1672515782136, // Event time
|
||||
"s": "BNBBTC", // Symbol
|
||||
"k": {
|
||||
"t": 1672515780000, // Kline start time
|
||||
"T": 1672515839999, // Kline close time
|
||||
"s": "BNBBTC", // Symbol
|
||||
"i": "1m", // Interval
|
||||
"f": 100, // First trade ID
|
||||
"L": 200, // Last trade ID
|
||||
"o": "0.0010", // Open price
|
||||
"c": "0.0020", // Close price
|
||||
"h": "0.0025", // High price
|
||||
"l": "0.0015", // Low price
|
||||
"v": "1000", // Base asset volume
|
||||
"n": 100, // Number of trades
|
||||
"x": false, // Is this kline closed?
|
||||
"q": "1.0000", // Quote asset volume
|
||||
"V": "500", // Taker buy base asset volume
|
||||
"Q": "0.500", // Taker buy quote asset volume
|
||||
"B": "123456" // Ignore
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Kline/Candlestick Streams with timezone offset
|
||||
|
||||
The Kline/Candlestick Stream push updates to the current klines/candlestick every second in `UTC+8` timezone
|
||||
|
||||
**Kline/Candlestick chart intervals:**
|
||||
|
||||
Supported intervals: See [`Kline/Candlestick chart intervals`](https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#kline-intervals)
|
||||
|
||||
**UTC+8 timezone offset:**
|
||||
|
||||
- Kline intervals open and close in the `UTC+8` timezone. For example the `1d` klines will open at the beginning of the `UTC+8` day, and close at the end of the `UTC+8` day.
|
||||
- Note that `E` (event time), `t` (start time) and `T` (close time) in the payload are Unix timestamps, which are always interpreted in UTC.
|
||||
|
||||
**Stream Name:** <symbol>@kline\_<interval>@+08:00
|
||||
|
||||
**Update Speed:** 1000ms for `1s`, 2000ms for the other intervals
|
||||
|
||||
**Payload:**
|
||||
|
||||
```javascript
|
||||
{
|
||||
"e": "kline", // Event type
|
||||
"E": 1672515782136, // Event time
|
||||
"s": "BNBBTC", // Symbol
|
||||
"k": {
|
||||
"t": 1672515780000, // Kline start time
|
||||
"T": 1672515839999, // Kline close time
|
||||
"s": "BNBBTC", // Symbol
|
||||
"i": "1m", // Interval
|
||||
"f": 100, // First trade ID
|
||||
"L": 200, // Last trade ID
|
||||
"o": "0.0010", // Open price
|
||||
"c": "0.0020", // Close price
|
||||
"h": "0.0025", // High price
|
||||
"l": "0.0015", // Low price
|
||||
"v": "1000", // Base asset volume
|
||||
"n": 100, // Number of trades
|
||||
"x": false, // Is this kline closed?
|
||||
"q": "1.0000", // Quote asset volume
|
||||
"V": "500", // Taker buy base asset volume
|
||||
"Q": "0.500", // Taker buy quote asset volume
|
||||
"B": "123456" // Ignore
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,287 @@
|
||||
# Trading Signals
|
||||
|
||||
   
|
||||
|
||||
Technical indicators and overlays to run [technical analysis](https://en.wikipedia.org/wiki/Technical_analysis) with JavaScript / TypeScript.
|
||||
|
||||
## Motivation
|
||||
|
||||
The "trading-signals" library provides a TypeScript implementation for common technical indicators. It is well-suited for algorithmic trading, allowing developers to perform signal computations for automated trading strategies.
|
||||
|
||||
All indicators can be updated over time by streaming data (prices or [candles](https://en.wikipedia.org/wiki/Candlestick_chart)) to the `add` method. Some indicators also provide `static` batch methods for further performance improvements when providing data up-front during a backtest or historical data import. You can try it out streaming input data by running the provided [demo script](./src/start/demo.ts) with `npm start`, which uses a keyboard input stream.
|
||||
|
||||
## Features
|
||||
|
||||
- **Streaming Updates:** No need to reprocess historical data
|
||||
- **Replace Mode:** Efficient live chart updates
|
||||
- **Lazy Evaluation:** Indicators only calculate when stable
|
||||
- **Memory Efficiency:** Rolling windows, not full history storage
|
||||
- **Excellent Test Coverage:** 100% across all metrics
|
||||
- **Zero Runtime Dependencies:** Minimal bundle size
|
||||
- **Type Safety:** Full TypeScript with strict mode
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm install trading-signals
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
**CommonJS:**
|
||||
|
||||
```ts
|
||||
const {SMA} = require('trading-signals');
|
||||
```
|
||||
|
||||
**ESM:**
|
||||
|
||||
```ts
|
||||
import {SMA} from 'trading-signals';
|
||||
```
|
||||
|
||||
**Example:**
|
||||
|
||||
```typescript
|
||||
import {SMA} from 'trading-signals';
|
||||
|
||||
const sma = new SMA(3);
|
||||
|
||||
// You can add values individually:
|
||||
sma.add(40);
|
||||
sma.add(30);
|
||||
sma.add(20);
|
||||
|
||||
// You can add multiple values at once:
|
||||
sma.updates([20, 40, 80]);
|
||||
|
||||
// You can replace a previous value (useful for live charting):
|
||||
sma.replace(40);
|
||||
|
||||
// You can check if an indicator is stable:
|
||||
console.log(sma.isStable); // true
|
||||
|
||||
// If an indicator is stable, you can get its result:
|
||||
console.log(sma.getResult()); // 50.0003
|
||||
|
||||
// You can also get the result without optional chaining:
|
||||
console.log(sma.getResultOrThrow()); // 50.0003
|
||||
|
||||
// Various precisions are available too:
|
||||
console.log(sma.getResultOrThrow().toFixed(2)); // "50.00"
|
||||
console.log(sma.getResultOrThrow().toFixed(4)); // "50.0003"
|
||||
|
||||
// Each indicator also includes convenient features such as "lowest" and "highest" lifetime values:
|
||||
console.log(sma.lowest?.toFixed(2)); // "23.33"
|
||||
console.log(sma.highest?.toFixed(2)); // "53.33"
|
||||
```
|
||||
|
||||
### When to use `add(...)`?
|
||||
|
||||
To input data, you need to call the indicator's `add` method. Depending on whether the minimum required input data for the interval has been reached, the `add` method may or may not return a result from the indicator.
|
||||
|
||||
### When to use `getResultOrThrow()`?
|
||||
|
||||
You can call `getResultOrThrow()` at any point in time, but it throws errors unless an indicator has received the minimum amount of data. If you call `getResultOrThrow()` before an indicator has received the required amount of input values, a `NotEnoughDataError` will be thrown.
|
||||
|
||||
**Example:**
|
||||
|
||||
```ts
|
||||
import {SMA} from 'trading-signals';
|
||||
|
||||
// Our interval is 3, so we need 3 input values
|
||||
const sma = new SMA(3);
|
||||
|
||||
// We supply 2 input values
|
||||
sma.add(10);
|
||||
sma.add(40);
|
||||
|
||||
try {
|
||||
// We will get an error, because the minimum amount of inputs is 3
|
||||
sma.getResultOrThrow();
|
||||
} catch (error) {
|
||||
console.log(error.constructor.name); // "NotEnoughDataError"
|
||||
}
|
||||
|
||||
// We will supply the 3rd input value
|
||||
sma.add(70);
|
||||
|
||||
// Now, we will receive a proper result
|
||||
console.log(sma.getResultOrThrow()); // 40
|
||||
```
|
||||
|
||||
Most of the time, the minimum amount of data depends on the interval / time period used. If you're not sure, take a look at the test files for the indicator to see examples of correct usage.
|
||||
|
||||
### When to use `getRequiredInputs()`?
|
||||
|
||||
Every indicator provides a `getRequiredInputs()` method that returns the minimum number of input values needed before the indicator becomes stable and can produce results. This is useful for validation and understanding when an indicator will start producing return values.
|
||||
|
||||
**Example:**
|
||||
|
||||
```ts
|
||||
import {SMA, EMA, RSI} from 'trading-signals';
|
||||
|
||||
const sma = new SMA(5);
|
||||
console.log(sma.getRequiredInputs()); // 5
|
||||
```
|
||||
|
||||
The required inputs often depend on the indicator's configuration (like interval/period) and its internal calculation requirements. Some indicators like **MACD** or **Stochastic Oscillator** may require more inputs than their primary period because they use multiple moving averages or lookback periods internally.
|
||||
|
||||
### When to use `getSignal()`?
|
||||
|
||||
Many momentum and trend indicators provide a `getSignal()` method that returns the current trading signal state along with change detection. This is useful for identifying potential trading opportunities.
|
||||
|
||||
**Example:**
|
||||
|
||||
```ts
|
||||
import {RSI} from 'trading-signals';
|
||||
|
||||
const rsi = new RSI(14);
|
||||
|
||||
// Add price data
|
||||
// ...
|
||||
|
||||
// Get the trading signal
|
||||
const signal = rsi.getSignal();
|
||||
console.log(signal.state); // "BEARISH", "BULLISH", "SIDEWAYS", or "UNKNOWN"
|
||||
console.log(signal.hasChanged); // true if the signal state changed from the previous value
|
||||
```
|
||||
|
||||
## Technical Indicator Types
|
||||
|
||||
### Indicator Function
|
||||
|
||||
- Momentum indicators: Measure the speed and strength (intensity) of price movements in a particular direction (overbought/oversold)
|
||||
- Trend indicators: Measure the direction of a trend (bullish/bearish)
|
||||
- Volatility indicators: Measure the degree of variation in prices over time, regardless of direction
|
||||
- Volume indicators: Measure the strength of a trend based on volume
|
||||
|
||||
**Key readings:**
|
||||
|
||||
- Bullish sentiment: expect prices to rise
|
||||
- Bearish sentiment: expect prices to fall
|
||||
- Overbought condition: price may have risen too much too fast, meaning it’s trending up, but traders expect a short-term dip before continuing higher
|
||||
- Oversold condition: price may have dropped too much too fast, meaning it’s trending down, but traders expect a short-term bounce before continuing lower or reversing upward
|
||||
|
||||
### Indicator Timing
|
||||
|
||||
- Leading Indicators: Predictive tools that try to signal future price movements before they happen (i.e. RSI, Stochastic Oscillator, Volume spikes)
|
||||
- Lagging Indicators: Confirmative tools that signal after a trend or move has already started (i.e. Moving Averages, MACD, ADX)
|
||||
|
||||
### Indicator Scale
|
||||
|
||||
- Indicators: Have no upper or lower limits
|
||||
- Oscillators: Move within a fixed range (e.g. 0-100, –1 to +1)
|
||||
|
||||
## Supported Technical Indicators
|
||||
|
||||
1. Acceleration Bands (ABANDS)
|
||||
1. Accelerator Oscillator (AC)
|
||||
1. Average Directional Index (ADX)
|
||||
1. Average True Range (ATR)
|
||||
1. Awesome Oscillator (AO)
|
||||
1. Bollinger Bands (BBANDS)
|
||||
1. Bollinger Bands Width (BBW)
|
||||
1. Center of Gravity (CG)
|
||||
1. Commodity Channel Index (CCI)
|
||||
1. Directional Movement Index (DMI / DX)
|
||||
1. Double Exponential Moving Average (DEMA)
|
||||
1. Dual Moving Average (DMA)
|
||||
1. Exponential Moving Average (EMA)
|
||||
1. Interquartile Range (IQR)
|
||||
1. Linear Regression (LINREG)
|
||||
1. Mean Absolute Deviation (MAD)
|
||||
1. Momentum (MOM / MTM)
|
||||
1. Moving Average Convergence Divergence (MACD)
|
||||
1. On-Balance Volume (OBV)
|
||||
1. Parabolic SAR (PSAR)
|
||||
1. Range Expansion Index (REI)
|
||||
1. Rate-of-Change (ROC)
|
||||
1. Relative Moving Average (RMA)
|
||||
1. Relative Strength Index (RSI)
|
||||
1. Simple Moving Average (SMA)
|
||||
1. Spencer's 15-Point Moving Average (SMA15)
|
||||
1. Stochastic Oscillator (STOCH)
|
||||
1. Stochastic RSI (STOCHRSI)
|
||||
1. Tom Demark's Sequential Indicator (TDS)
|
||||
1. True Range (TR)
|
||||
1. Volume-Weighted Average Price (VWAP)
|
||||
1. Weighted Moving Average (WMA)
|
||||
1. Wilder's Smoothed Moving Average (WSMA / WWS / SMMA / MEMA)
|
||||
1. Williams %R (WILLR)
|
||||
1. Zig Zag Indicator (ZigZag)
|
||||
|
||||
Utility Methods:
|
||||
|
||||
1. Average / Mean
|
||||
1. Grid Sizing (for [grid trading bots](https://b2broker.com/news/understanding-grid-trading-purpose-pros-cons/))
|
||||
1. Maximum
|
||||
1. Median
|
||||
1. Minimum
|
||||
1. Quartile
|
||||
1. Standard Deviation
|
||||
1. Streaks
|
||||
1. Weekday
|
||||
|
||||
## Performance
|
||||
|
||||
### Floating-point arithmetic caveats
|
||||
|
||||
JavaScript uses double-precision floating-point arithmetic. For example, `0.1 + 0.2` yields `0.30000000000000004` due to binary floating-point representation.
|
||||
|
||||

|
||||
|
||||
While this isn’t perfectly accurate, it usually doesn’t matter in practice since indicators often work with averages, which already smooth out precision. In test cases, you can control precision by using Vitest’s [toBeCloseTo](https://vitest.dev/api/expect.html#tobecloseto) assertion.
|
||||
|
||||
Earlier versions of this library (up to version 6) used [big.js][1] for arbitrary-precision arithmetic, but that made calculations about 100x slower on average. For this reason, support for [big.js][1] was removed starting with version 7.
|
||||
|
||||
## Disclaimer
|
||||
|
||||
The information and publications of [trading-signals](https://github.com/bennycode/trading-signals) do not constitute financial advice, investment advice, trading advice or any other form of advice. All results from [trading-signals](https://github.com/bennycode/trading-signals) are intended for information purposes only.
|
||||
|
||||
It is very important to do your own analysis before making any investment based on your own personal circumstances. If you need financial advice or further advice in general, it is recommended that you identify a relevantly qualified individual in your jurisdiction who can advise you accordingly.
|
||||
|
||||
## Alternatives
|
||||
|
||||
- [Cloud9Trader Indicators (JavaScript)](https://github.com/Cloud9Trader/TechnicalIndicators)
|
||||
- [Crypto Trading Hub Indicators (TypeScript)](https://github.com/anandanand84/technicalindicators)
|
||||
- [Highcharts Indicators (TypeScript)](https://github.com/highcharts/highcharts/tree/v12.3.0/ts/Stock/Indicators)
|
||||
- [Indicator TS (TypeScript)](https://github.com/cinar/indicatorts)
|
||||
- [Jesse Trading Bot Indicators (Python)](https://docs.jesse.trade/docs/indicators/reference.html)
|
||||
- [LEAN Indicators (C#)](https://github.com/QuantConnect/Lean/tree/master/Indicators)
|
||||
- [libindicators (C#)](https://github.com/mgfx/libindicators)
|
||||
- [Pandas TA (Python)](https://github.com/twopirllc/pandas-ta)
|
||||
- [Stock Indicators for .NET (C#)](https://github.com/DaveSkender/Stock.Indicators)
|
||||
- [StockSharp (C#)](https://github.com/StockSharp/StockSharp)
|
||||
- [ta-lib (C)](https://github.com/TA-Lib/ta-lib/tree/main/src/ta_func)
|
||||
- [ta-math (TypeScript)](https://github.com/munrocket/ta-math)
|
||||
- [ta4j (Java)](https://github.com/ta4j/ta4j)
|
||||
- [Technical Analysis for Rust (Rust)](https://github.com/greyblake/ta-rs)
|
||||
- [Technical Analysis Library using Pandas and Numpy (Python)](https://github.com/bukosabino/ta)
|
||||
- [Tulip Indicators (ANSI C)](https://github.com/TulipCharts/tulipindicators)
|
||||
|
||||
## Documentation
|
||||
|
||||
Build and run the documentation:
|
||||
|
||||
```bash
|
||||
npm run docs
|
||||
```
|
||||
|
||||
## Maintainers
|
||||
|
||||
[![Benny Neugebauer on Stack Exchange][stack_exchange_bennycode_badge]][stack_exchange_bennycode_url]
|
||||
|
||||
## ⭐️ Become a TypeScript rockstar! ⭐️
|
||||
|
||||
This package was built by Benny Neugebauer. Checkout my [**TypeScript course**](https://typescript.tv/) to become a coding rockstar!
|
||||
|
||||
[<img src="https://raw.githubusercontent.com/bennycode/trading-signals/main/packages/trading-signals/tstv.png">](https://typescript.tv/)
|
||||
|
||||
[1]: http://mikemcl.github.io/big.js/
|
||||
[stack_exchange_bennycode_badge]: https://stackexchange.com/users/flair/203782.png?theme=default
|
||||
[stack_exchange_bennycode_url]: https://stackexchange.com/users/203782/benny-neugebauer?tab=accounts
|
||||
|
||||
## License
|
||||
|
||||
This project is [MIT](./LICENSE) licensed.
|
||||
@@ -0,0 +1,43 @@
|
||||
# Swing strategy (RSI on Binance ETHBTC)
|
||||
|
||||
This repo’s `swing` strategy **trades the exchange symbol you run the bot with** (e.g. `TRADE_SYMBOL`), but **uses Binance spot `ETHBTC` 4h RSI(14)** as the global signal source (per `docs/swingtrading/strategy.md`).
|
||||
|
||||
## Key behavior
|
||||
|
||||
- **Signal source**: Binance spot `ETHBTC`, `4h` klines, RSI period `14`.
|
||||
- **Trade target**: your selected exchange’s `TRADE_SYMBOL` / `*_SYMBOL` (same as other strategies).
|
||||
- **Default mode**: short-only (configurable to long / short / both).
|
||||
- **Stop-loss**:
|
||||
- Tries to place a stop-loss order when supported by the venue.
|
||||
- Always runs a real-time “kill-switch”: if price crosses the stop threshold, it market-closes.
|
||||
- **Spot accounts**: if the connected account is `marketType=spot` and you configure `SWING_DIRECTION=short` (or `both`), the strategy will refuse to trade.
|
||||
|
||||
## Environment variables
|
||||
|
||||
- **Core**
|
||||
- `SWING_DIRECTION`: `short` (default) | `long` | `both`
|
||||
- `SWING_TRADE_AMOUNT`: position size (falls back to `TRADE_AMOUNT`)
|
||||
- `SWING_POLL_INTERVAL_MS`: loop interval (default `500`)
|
||||
- **RSI / signal**
|
||||
- `SWING_RSI_PERIOD`: default `14`
|
||||
- `SWING_RSI_HIGH`: default `70`
|
||||
- `SWING_RSI_LOW`: default `30`
|
||||
- `SWING_SIGNAL_SYMBOL`: default `ETHBTC`
|
||||
- `SWING_SIGNAL_INTERVAL`: default `4h`
|
||||
- **Risk / precision**
|
||||
- `SWING_STOP_LOSS_PCT`: default `0.05` (5%)
|
||||
- `SWING_MAX_CLOSE_SLIPPAGE_PCT`: default `0.05`
|
||||
- `SWING_PRICE_TICK`, `SWING_QTY_STEP`: optional overrides (otherwise synced from exchange when supported)
|
||||
|
||||
## Run
|
||||
|
||||
```bash
|
||||
bun run index.ts --strategy swing
|
||||
```
|
||||
|
||||
Silent mode:
|
||||
|
||||
```bash
|
||||
bun run index.ts --strategy swing --silent
|
||||
```
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
无论在任何交易所或者平台运行,都遵循以下逻辑:
|
||||
|
||||
无论交易任何交易对,都参照 ETHBTC 数据进行交易
|
||||
|
||||
从binance现货接口获取 ETHBTC 交易对 4 小时k线数据,rest 接口获取历史数据,获取500条即可
|
||||
|
||||
订阅ws获取最新一根K线的数据
|
||||
|
||||
参考 trading-signals 库,计算 RSI 指标,RSI 参数为 14
|
||||
|
||||
我们的策略仅单边做空,但需要预留配置,可以支持单边做多,单边做空,双向交易
|
||||
|
||||
下面针对单边做空的情况进行说明
|
||||
|
||||
RSI 指标上穿 70 时,进入等待做空状态,后续当 RSI 指标下穿 70 时,执行做空开仓操作
|
||||
|
||||
如果对应的平台支持挂止损 stop loss,则在开仓的同时需要挂一个开仓成本价上涨 5% 的止损单,止损百分比可以设置参数调整,同时也需要有实时监控的止损逻辑,如果在持仓状态下,当前交易对比开仓价格上涨超过 5% ,则执行主动的市价止损操作
|
||||
|
||||
策略需要实时监控当前的交易对ticker数据、orderbook数据,open orders、position,支持ws的全都使用ws数据实时更新
|
||||
|
||||
在有仓位的情况下,如果发现 ETHBTC 的 RSI 指标下穿 30,则进入等待平空状态,如果后续 RSI 指标上穿 30,并且确认仓位有盈利,则执行平空操作
|
||||
|
||||
如此循环往复
|
||||
|
||||
Reference in New Issue
Block a user